I want to create a double-bar plot
from a dataset similar to the following data:
df <- data.frame(
month=c("2","3","11","3","4","1","5","3","12","11","10","9","9","7","5","3","2","5","12","10"),
member_casual=c("member","casual","member","casual","member","casual","casual","casual","member","casual",
"member","casual","member","casual","member","casual","member","member","member","casual")
)
I want the x
to be the month
column, and the y
to be the count of each month's values.
I need double bars to represent member
and casual
.
I've done something similar to the following code but I couldn't calculate the count
of each month
.
ggplot(df, aes(x=x, y=y))+
geom_bar(stat = "identity", position = 'dodge')+
scale_x_continuous(breaks = 1:12)+
theme_classic()
This is an example of what it should look like Double bar example
I'm new to R and ggplot2 I hope that someone can help me.
You can get your desired result by using stat="count"
(which is the default for geom_bar
) which requires to drop y = y
. Additionally, to get a grouped bar chart you have to add your groups by mapping the grouping variable on fill
:
df <- data.frame(
month = c("2", "3", "11", "3", "4", "1", "5", "3", "12", "11", "10", "9", "9", "7", "5", "3", "2", "5", "12", "10"),
member_casual = c(
"member", "casual", "member", "casual", "member", "casual", "casual", "casual", "member", "casual",
"member", "casual", "member", "casual", "member", "casual", "member", "member", "member", "casual"
)
)
library(ggplot2)
ggplot(df, aes(as.numeric(month), fill = member_casual)) +
geom_bar(position = position_dodge(preserve = "single")) +
scale_x_continuous(breaks = 1:12) +
theme_classic()