I have a stacked bar graph with 2 numerical values and the bars are stacked on top of eachother. I would like to display a Legend that indicates the description of the 2 colors. Here it is my code but its not displaying. Any help from anyone I would be greatful for.
ggplot(data=my_data, aes(x = Xaxis))
ggtitle("My Title")
theme(plot.title = element_text(hjust = 0.5, face="bold"))
geom_col(aes(y = v1), fill ="red")
geom_col(aes(y = v2), fill="blue")
labs(y= "Amount", color ="Legend")
theme(legend.title = element_text(color='black',face='bold'),
legend.text = element_text(color='black',face='bold'))
scale_y_continuous(labels = comma)
From the above code the legend does not display
CodePudding user response:
Update: As I already mentioned in the comments you may consider another strategy with long format, but with your format you are in conflict with showing the legend of fill argument and getting the correct colors.
If you put the
fill
argument outside ofaes
no legend will be shown but you get the correct colors.If you put
fill
argument inside theaes
then the legend will be shown but the colors will be not as desired -> this is because you're basically generating a new factor variable and a legend.
First answer: try this:
ggplot(data=my_data, aes(x = Xaxis))
ggtitle("My Title")
theme(plot.title = element_text(hjust = 0.5, face="bold"))
geom_col(aes(y = v1, fill ="red"))
geom_col(aes(y = v2, fill="blue")))
labs(y= "Amount", color ="Legend")
theme(legend.title = element_text(color='black',face='bold'),
legend.text = element_text(color='black',face='bold'))
scale_y_continuous(labels = comma)
your code with the mtcars data set:
ggplot(data=mtcars, aes(x = cyl))
ggtitle("My Title")
theme(plot.title = element_text(hjust = 0.5, face="bold"))
geom_col(aes(y = disp, fill ="red"))
geom_col(aes(y = mpg, fill="blue"))
labs(y= "Amount", color ="Legend")
theme(legend.title = element_text(color='black',face='bold'),
legend.text = element_text(color='black',face='bold'))