Reputation: 411
I'm really new to ggplot2 but trying to learn. I have my data in long form and it looks like this:
Year School Type Stat Value
2011 Middle School Tobacco Use 7.5
2011 Middle School Cigarettes 4.3
2011 Middle School Smokeless Tobacco 2.2
2011 Middle School Hookahs 1
2011 Middle School E-cigarettes 0.6
2011 High School Tobacco Use 24.3
2011 High School Cigarettes 15.8
2011 High School Smokeless Tobacco 7.3
2011 High School Hookahs 4.1
2011 High School E-cigarettes 1.5
The full set is here: http://pastebin.com/VUvWhC4x
What I want to do is make two graphs, one for Middle School and one for High School. I can easily subset this into those groups so let's try for Middle School. I'm using a deplry verb here.
middle = as.data.frame(filter(data,School.Type=="Middle School"))
What I want the graph to look like is each stat will go along the x-axis and then the years will be graphed separately in a row for that year. Then move on to the next stat and the same thing. The years are 2011-2014. It's very much simulating this graph:
The best I can do is this code:
ggplot(middle, aes(factor(Stat), Value, fill = factor(Year)) +
+geom_bar(stat="identity", position = "dodge") +
+scale_fill_brewer(palette = "Set1")
I would like to group these by stat and then from year 2011-2014 for each stat. Any ideas?
Upvotes: 0
Views: 115
Reputation: 9582
You are close - you want Stat
mapped to the x axis and Value
to y. Then you fill by Year
and specify that the bars should be dodged (i.e. side by side).
This is pretty close to the plot you posted as the desired output.
library(ggplot2)
ggplot(middle, aes(x=Stat, y=Value, fill=factor(Year))) +
geom_bar(stat='identity', position ='dodge', color='black') +
scale_fill_brewer(palette=1) +
theme_classic()
Upvotes: 3