【问题标题】:Clustered Bar Plot Using ggplot2使用 ggplot2 的聚类条形图
【发布时间】:2019-11-30 08:18:05
【问题描述】:

基本上我想显示一个按方法分组的条形图,即我想显示进行测试的人数,每种方法发现的阳性测试结果的数量。另外,我想将所有数字和百分比显示为条形图上的标签。我正在尝试使用 ggplot2 显示这些。但我每次都失败了。

任何帮助。

提前致谢

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    我不确定是否完全理解您的问题。但我建议你看看geom_text

    library(ggplot2)
    
    ggplot(df, aes(x = methods, y = percentage)) + 
      geom_bar(stat = "identity") + 
      geom_text(aes(label = paste0(round(percentage,2), " (",positive," / ", people,")")), vjust = -0.3, size = 3.5)+
      scale_x_discrete(limits = c("NS1", "NS1+IgM", "NS1+IgG","Tourniquet")) + 
      ylim(0,100)
    

    数据:

    df = data.frame(methods = c("NS1", "NS1+IgM","NS1+IgG","Tourniquet"),
                    people = c(542,542,541,250),
                    positive = c(505,503,38,93))
    df$percentage = df$positive / df$people * 100
    
    > df
         methods people positive percentage
    1        NS1    542      505   93.17343
    2    NS1+IgM    542      503   92.80443
    3    NS1+IgG    541       38    7.02403
    4 Tourniquet    250       93   37.20000
    

    它回答了你的问题吗?如果没有,您能否通过在ggplot 中添加您迄今为止尝试过的代码来澄清您的问题?

    【讨论】:

    • 是的,它确实回答了我的问题。我正在使用以下代码。 >library(ggplot2) >library(reshape2) >df=data.frame(Methods=c('NS1', 'NS1+IgM', 'NS1+IgG', '止血带测试'), Positive=c(505,503,38 , 93), 百分比=c(93.2, 92.8,7.0,37.2)) >mm= melt(df, id.vars='Methods') >q=ggplot(mm, aes(x=Methods, y=value)) +geom_bar(stat='identity')+facet_grid(.~variable)+coord_flip()+labs(x='', y='') 非常感谢。
    • 很高兴它回答了您的问题。 (就个人而言,在您的代码中,我会写 facet_grid(.~variable, scales = 'free') 以获得更好的情节)。如果您认为这个问题已经结束,您可以查看此链接stackoverflow.com/help/someone-answers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 2017-09-27
    • 2021-04-24
    • 2017-08-04
    • 2015-01-03
    • 2021-03-14
    相关资源
    最近更新 更多