Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Plot dodged bar chart with line chart

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading