I want to somehow combine two plots, they have a common x axis but one is a faceted bar plot of categorical data. the other is continuous data and not faceted but relevant to the both facets on the first plot.
I have the following dummy data and code:
farm<- c(22, 33, 22, 33, 22, 33, 22, 33,
22, 33, 22, 33, 22, 33, 22, 33, 22, 33,
22, 33)
year<- c(2010, 2010, 2011, 2011, 2012, 2012, 2013, 2013,
2014, 2014, 2010, 2010, 2011, 2011, 2012, 2012, 2013,
2013, 2014, 2014)
exp<- c('a', 'a', 'a', 'a', 'a', 'a', 'a', 'a',
'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b',
'b', 'b', 'b')
variable1<- c(3, 1, 3, 1, 2, 0, 2,
1, 3, 0, 1, 1, 1, 0, 2, 0, 1,
0, 0, 0)
variable2<- c(300, 100, 400, 123, 500, 100, 600, 100,
700, 100, 700, 100, 600, 100, 700, 100, 600,
100, 300, 100)
dwt<-data.frame(farm, year, exp, variable1)
dwt2<-data.frame(farm, year, variable2)
dwt$farm<- as.character(dwt$farm)
dwt %>%
mutate(as.character(farm))%>%
mutate(as.character(year))%>%
mutate(as.character(variable1))%>%
ggplot(aes(x=farm, fill = variable1)) +
geom_bar(stat = 'count') + facet_grid(exp~year) +
guides(fill=guide_legend(title="Level")) +
coord_cartesian(ylim=c(0, 5))
dwt2$farm<- as.character(dwt2$farm)
dwt2 %>%
mutate(as.character(farm))%>%
mutate(as.character(year))%>%
ggplot(aes(x=farm, y = variable2)) +
geom_bar(stat = 'identity') + facet_grid(~year) +
guides(fill=guide_legend(title="Level"))
This gives the following plots:
Also I have searched for other questions and tried the following:
ggplot()+
geom_bar(data=dwt, aes(x=farm, fill=variable1))+ facet_grid(exp~year) +
geom_bar(data = dwt2, aes(x=farm, y=variable2))+ facet_grid(~year)
but get the following error: Aesthetics must be either length 1 or the same as the data (20): x, y
Which I think may be due to the faceting
Any help will be appreciated. Also I would prefer to use two data frames rather than combine if possible.