Home > Back-end >  I want to add a total at the top of my bar chart using ggplot2 in R. When I try, I'm getting th
I want to add a total at the top of my bar chart using ggplot2 in R. When I try, I'm getting th

Time:11-05

I'm fairly new to R and have created a bar chart using

ggplot(df_mountainorframemodelsales, aes(x = FrameOrMountain, y = salestotal, fill= FrameOrMountain))  
  geom_bar(stat = "identity") 
  ggtitle("Frame and Mountain Bikes Total Sales") 

Which gives me a standard chart with two columns. I want to add a total at the top of each column, however when I try it is giving me a big cluster of numbers at the bottom of the chart. I think it is each individual total rather than the sum of them all together. How do I get the total for all mountains and all frames?

This is the code I've tried

ggplot(df_mountainorframemodelsales, aes(x = FrameOrMountain, y = salestotal, fill= FrameOrMountain))  
  geom_bar(stat = "identity")  
  geom_text(aes(label=salestotal), vjust=0)  
  ggtitle("Frame and Mountain Bikes Total Sales")

this is what I get

I've tried searching for answers but all the other problems are with stacked bar charts. Can anyone help please?

CodePudding user response:

You can change the data= used by specific geoms, such as

ggplot(mtcars, aes(x = cyl, y = disp, fill = cyl))  
  geom_bar(stat = "identity")  
  geom_text(aes(label = disp), vjust = 0,
            data = ~ aggregate(disp ~ cyl, data = ., FUN = sum))  
  ggtitle("Total Displacement by Number of Cylinders")

enter image description here

This highlights that you may want to expand= the y-axis to allow room for the top labels. Alternatively, you can change vjust=1.2 or some number over 1 so that it is enclosed within the bar, though this will have problems when bars have extremely low totals (so I think expand= with vjust=0 is safer).

(I'm not saying this is an awesome plot: cyl being shown as a discrete vice continuous variable would make a lot of sense, and perhaps other aspects that would make this comparison better. My point of not doing that was to stay as close to your original code as possible.)

  • Related