Reputation: 23
I'm plotting a stacked bar chart using ggplot2. I've created a dataframe (df_car) with the variables car_make
, color
and proportion
, the latter being numerical. There are 20 types of car_make
which go along the x-axis, and 4 of color
which go as fills. The proportion for each car_make
adds up to 1.
I didn't want the car_make
in alphabetical order so I re-ordered it:
df_car$car_make <- factor(df_car$car_make, levels = c("toyota", "ford", "mercedes", etc.)
Then I re-ordered the fill levels:
df_car$color <- factor(df_car$color, levels = c("red", "white", "black", "silver")
I plot the stacked bar plot:
bp_car<- ggplot(df_car, aes(x=car_make, y=proportion, fill=color)) + geom_bar(stat="identity")
The x-axis comes out as I specified. But the order of the bar fills remains alphabetical...only the order of the legend responds and comes out as specified. Performing...
levels(df_car$color)
gives...
"red", "white", "black", "silver"
How can I get the bar fills to re-order?
Upvotes: 2
Views: 976
Reputation: 146224
You don't need a data column with color names in it (ggplot is different from base graphics in this way). Once your car levels are ordered appropriately (as you've done), you need to set a fill color scale
bp_car <- ggplot(df_car, aes(x = car_make, y = proportion, fill = car_make)) +
geom_bar(stat="identity") +
scale_fill_manual(values = c("red", "white", "black", "silver"))
Upvotes: 1