Creating simple stacked bar graphs
Stacked bars are often settled to display how data is distributed across categories with respect to other categories. Using ggplot2, stacked bar plots can be simply handled by geom_bar() function; that would require nothing more than explicitly declaring the fill parameter. To demonstrate how ggplot2, ggvis and plotly can craft simple stacked bar plots we shall use car::Salaries data frame.
Getting ready
The data frame is Salaries from the car package. We also need the plyr package:
> if( !require(car)){ install.packages('car')}
> if( !require(plyr)){ install.packages('plyr')}Make sure to have the internet connection before running above code.
How to do it...
After looking at the data, ggplot2 can deploy stacked bars by naming the fill argument:
- Call the
geom_bar()function to make sure to have the bar geometry:
> library(ggplot2) > gg2_sal <- ggplot( data = car::Salaries, aes(x = rank)) > gg2_sal + geom_bar(aes(fill = sex))
Check the following...