How to plot a combined bar and line plot in ggplot2

前端 未结 1 1276
粉色の甜心
粉色の甜心 2021-01-13 18:26

I have the following data which I am trying to plot as combined bar and line plot (with CI)

A data frame of Feature, Count, Odds Ratio and Confidence Interval values

相关标签:
1条回答
  • 2021-01-13 18:57

    Is this what you had in mind?

    ratio <- max(feat$Count)/max(feat$CI2)
    ggplot(feat) +
      geom_bar(aes(x=Feat, y=Count),stat="identity", fill = "steelblue") +
      geom_line(aes(x=Feat, y=OR*ratio),stat="identity", group = 1) +
      geom_point(aes(x=Feat, y=OR*ratio)) +
      geom_errorbar(aes(x=Feat, ymin=CI1*ratio, ymax=CI2*ratio), width=.1, colour="orange", 
                    position = position_dodge(0.05)) +
        scale_y_continuous("Count", sec.axis = sec_axis(~ . / ratio, name = "Odds Ratio"))
    

    Edit: Just for fun with the legend too.

    ggplot(feat) +
      geom_bar(aes(x=Feat, y=Count, fill = "Count"),stat="identity") + scale_fill_manual(values="steelblue") +
      geom_line(aes(x=Feat, y=OR*ratio, color = "Odds Ratio"),stat="identity", group = 1) + scale_color_manual(values="orange") +
      geom_point(aes(x=Feat, y=OR*ratio)) +
      geom_errorbar(aes(x=Feat, ymin=CI1*ratio, ymax=CI2*ratio), width=.1, colour="orange", 
                    position = position_dodge(0.05)) +
      scale_y_continuous("Count", sec.axis = sec_axis(~ . / ratio, name = "Odds Ratio")) +  
      theme(legend.key=element_blank(), legend.title=element_blank(), legend.box="horizontal",legend.position = "bottom")
    

    Since you asked about adding p values for comparisons in the comments, here is a way you can do that. Unfortunately, because you don't really want to add **all* the comparisons, there's a little bit of hard coding to do.

    library(ggplot2)
    library(ggsignif)
    ggplot(feat,aes(x=Feat, y=Count)) +
      geom_bar(aes(fill = "Count"),stat="identity") + scale_fill_manual(values="steelblue") +
      geom_line(aes(x=Feat, y=OR*ratio, color = "Odds Ratio"),stat="identity", group = 1) + scale_color_manual(values="orange") +
      geom_point(aes(x=Feat, y=OR*ratio)) +
      geom_errorbar(aes(x=Feat, ymin=CI1*ratio, ymax=CI2*ratio), width=.1, colour="orange", 
                    position = position_dodge(0.05)) +
      scale_y_continuous("Count", sec.axis = sec_axis(~ . / ratio, name = "Odds Ratio")) +  
      theme(legend.key=element_blank(), legend.title=element_blank(), legend.box="horizontal",legend.position = "bottom") + 
      geom_signif(comparisons = list(c("A","H"),c("B","F"),c("D","E")),
                  y_position = c(150,60,40),
                  annotation = c("***","***","n.s."))
    

    0 讨论(0)
提交回复
热议问题