【问题标题】:Is it possible to draw a percentage stacked barplot when you only have samples+variable percentages?当您只有样本+可变百分比时,是否可以绘制百分比堆积条形图?
【发布时间】:2020-09-04 13:01:02
【问题描述】:
df <- data.frame(sd = c('05AP.U1 1 ','05AP.U2 1','07RT.U1 1'),percentpl = c(50,40,80),percentan = c(50,60,20),count = c(100,100,100))

sd        percentpl  percentan  count
1  05AP.U1       50        50   100
9  03KM.U2       40        60   100 
12 07RT.U1       80        20   100

是否可以仅在df 的基础上绘制堆叠百分比条形图。我用ggplot 尝试过,但在fill 变量上失败了。

ggplot(df, aes(fill=`percentpl`+`percentan`, y=count, x=`sd`)) + 
    geom_bar(position="fill", stat="identity")+ theme(axis.text = element_text(angle = 90))

我还看到过其他几个类似的问题R ggplot2 stacked barplot, percent on y axis, counts in barsAdd percentage labels to a stacked barplot

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    也许你正在寻找这个。由于 percentplpercentan 中的值,您的 count 变量增加到 100,您可以根据这些变量重新整形并获得填充图:

    library(ggplot2)
    library(tidyverse)
    #Data
    df <- data.frame(sd = c('05AP.U1 1 ','05AP.U2 1','07RT.U1 1'),
                     percentpl = c(50,40,80),
                     percentan = c(50,60,20),
                     count = c(100,100,100))
    #Melt and plot
    df %>% select(-count) %>%
      pivot_longer(cols = -sd) %>%
      ggplot(aes(x=sd,y=value,fill=name)) + 
      geom_bar(position="fill", stat="identity")+
      theme(axis.text = element_text(angle = 90))
    

    输出:

    【讨论】:

      猜你喜欢
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 2021-12-22
      • 1970-01-01
      • 2021-05-31
      • 2018-03-15
      相关资源
      最近更新 更多