Reputation: 85
I am new to using ggplot2 and i am having trouble plotting a graph. I have looked around on SO but the solutions I found did not work with my data. Here is an example of my DF
Count1 Count2 Color
3 4 Red
3 6 Green
5 2 Red
2 0 Blue
I would like to just plot this is as a bar graph. I would like the X axis to consist of the colors and I would like to plot both the Count1 and Count2 variables on the y axis. for example, the two bars used to show the green
color will go up to the number 3 (for count1
) and the number 6 (for count2
). Similarly, the red
bar will go up to 8 (for count1
) and 6 (for count2
) Does anyone know how to go about doing this? Thanks!
Upvotes: 0
Views: 1384
Reputation: 1297
Breaking up the answer from @alistaire above, so you can follow what's going on
Your data
color_df <- data.frame(Count1 = c(3,3,5,2), Count2 = c(4,6,2,0), Color = c("Red", "Green", "Red", "Blue"))
Adding up counts for each color
library(dplyr)
sum_df <- color_df %>%
group_by(Color) %>%
summarise_all(sum)
sum_df
ggplot needs both counts in one column, with another column describing which is which. Compare sum_df
and tidy_df
library(tidyr)
tidy_df <- sum_df %>%
gather(CountName, Count, -Color)
Finally the plot. Dodge puts them side by side. geom_col
uses heights from Count
variable. geom_bar
would count number of observations itself.
library(ggplot2)
ggplot(tidy_df, aes(x = Color, fill = CountName, y = Count)) +
geom_col(position = "dodge")
Upvotes: 2