Home > Software design >  Plot dodged bar chart with line chart
Plot dodged bar chart with line chart

Time:03-10

Im struggling hard trying to make this chart happen using ggplot2:

enter image description here

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

CodePudding user response:

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")

enter image description here

A couple of other things to note here:

  1. Remember aesthetics are inherited from the initial ggplot call, so if all your layers have x = Month, put aes(x = Month) inside the initial ggplot call. This simplifies your code, reduces repetition and therefore reduces the chance of errors creeping in.
  2. geom_bar(stat = "identity") is just a longer way of writing geom_col()
  3. 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.
  • Related