【问题标题】:colored 100% barplot with ggplot2用 ggplot2 着色 100% 条形图
【发布时间】:2016-05-08 19:14:16
【问题描述】:

我对 R 完全陌生,刚刚免除了 edX 的介绍。不幸的是,它没有教任何关于 ggplot2 的内容,我想在我的论文中的图表中使用什么。我想获得具有不同颜色的 100% 条形图,如果可能的话,在相应的条形图中获得值。我的数据如下所示:

Concentration,Percentage,Phenotype
Control,0.933333333,0
Control,0.014814815,1
Control,0.022222222,2
Control,0.02962963,3
0.002,0.918181818,0
0.002,0.018181818,1
0.002,0.018181818,2
0.002,0.045454545,3
0.02,0.930434783,0
0.02,0.017391304,1
0.02,0.017391304,2
0.02,0.034782609,3
0.2,0.928571429,0
0.2,0.032467532,1
0.2,0.012987013,2
0.2,0.025974026,3
2,0.859813084,0
2,0.028037383,1
2,0.046728972,2
2,0.065420561,3

我使用的代码是这样的:

ggplot(Inj, aes(x=Concentration, y=Percentage, fill=Phenotype))+geom_bar(stat='identity',color='black')

生成的图表如下所示:

如何更改不同条形的颜色并获取条形中的百分比值?

感谢您的帮助

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    您可以通过将填充变量作为一个因素来控制颜色。然后你可以像这样手动调整颜色

    ggplot(Inj, aes(x=Concentration, y=Percentage, fill=factor(Phenotype)))+geom_bar(stat='identity',color='black') +
      scale_fill_manual(values=c("red", "blue", "yellow", "pink"))
    

    我不建议将值放在颜色上,因为它们对于非常小的值是不可见的。我会使用另一种方式来可视化数据。

    【讨论】:

      【解决方案2】:

      您可以使用scale_x_discrete 手动重新排序因子,如下所示:

      ggplot(Inj, aes(x=Concentration, y=Percentage, fill=Phenotype)) + 
        geom_bar(stat='identity',color='black') +
        scale_fill_grey(start = .4, end = .9) + 
        theme_bw()+ylab("Distribution") + 
        xlab("Contentration [mg/ml]") + 
        ggtitle("Dose-respond analysis") +
        theme(legend.title = element_text(colour="black", size=10, face="bold")) +
        theme(legend.background = element_rect(fill="white",
                                         size=0.5, linetype="solid", 
                                         colour ="black")) +
        scale_x_discrete(limits=c('Control','0.002', '0.02', '0.2', '2'),
                         labels=c('Control\n(N=000)',
                                  '0.002\n(N=000)', 
                                  '0.02\n(N=000)', 
                                  '0.2\n(N=000)', 
                                  '2\n(N=000)'))
      

      我将labels 部分添加到scale_x_discrete,以回答您在下面的cmets 中提出的问题。您只需要更新 N 个值。请注意,我将\n 放在每个标签中,以便将标签文本强制为两行,这样它就不会混乱。如果您希望它位于一行,只需删除 \n

      【讨论】:

      • 好的,谢谢!最后一件事是用观察到的个体数量标记每个条形图。像 n=158 或类似的东西用于控制,n=145 用于 0.002 等等。那可能吗?我在互联网上发现的唯一一件事就是添加条的实际值,但我想单独标记每个条。
      • 刚刚编辑了答案以包含此问题的解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      相关资源
      最近更新 更多