'Plot dodged bar chart with line chart
Im struggling hard trying to make this chart happen using ggplot2:
This is my code so far, im able to plot the lines but not the dodge bars:
df <- data.frame (Month=c("A","B","C","D","D","D"),Red = c(0.08,0.06,0.04,0,0,0)
,Green =c(80,100,90,0,0,0),Purple=c(5,10,3,0,0,0),Prom =
c(0,0,0,0.06,90,3),Group=c(1,1,1,2,2,2))
ggplot(df)+geom_line(aes(x=Month, y=Red, group=Group))+geom_line(aes(x=Month, y=Green,
group=Group))+geom_bar(aes(x=Month,y=Prom,group=Group,fill=as.factor(Prom)),
position="dodge",stat="identity")
Do i have to modify my dataframe?, all i need is the dodge part and im able to do the rest of the plot
thanks
Solution 1:[1]
Remove the Group variable from the bar's aesthetic mapping. It is trying to dodge based on this, but all the fills have the same Group, so no dodging occurs
ggplot(df, aes(x = Month)) +
geom_line(aes(y = Red, group = Group)) +
geom_line(aes(y = Green, group = Group)) +
geom_col(aes(y = Prom, fill = as.factor(Prom)), position = "dodge")
A couple of other things to note here:
- Remember aesthetics are inherited from the initial
ggplotcall, so if all your layers havex = Month, putaes(x = Month)inside the initial ggplot call. This simplifies your code, reduces repetition and therefore reduces the chance of errors creeping in. geom_bar(stat = "identity")is just a longer way of writinggeom_col()- Formatting your code to have spaces and line breaks at appropriate points makes it much easier to debug when problems come up. This is not the minor point that you may assume. Getting into the habit of writing tidy and legible code saves you a lot of time and effort in the long run.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |


