【问题标题】:Trying to plot stacked barplot from percentages试图从百分比绘制堆积条形图
【发布时间】:2019-05-27 12:14:34
【问题描述】:

我正在尝试绘制不同部门计算机使用率的堆积条形图,并详细说明每个条形图中的 PC 类型(以便每个部门 type1+type2+type3=tot_rate)。我有一个看起来像这样的数据框:

dat=read.table(text = "Tot_rate   Type1   Type2   Type3
DPT1 72 50 12 10 
DPT2 80 30 20 30
DPT3 92 54 14 24", header = TRUE)

我试图用原始数据绘制我的条形图,但现在获得带有百分比的条形图非常重要,但我似乎无法理解如何做到这一点。

这就是我认为我可以做到的方式,但它不起作用

p<-ggplot(dat, aes(x=row.names(dat), y=dat$Tot_rate, fill=data[,2:ncol(dat)])) + geom_bar(stat="identity")+theme_minimal()+xlab("") + ylab("PC rate")+geom_abline(slope=0, intercept=90,  col = "red",lty=2) + theme(axis.text.x = element_text(angle = 90, hjust = 1))
p

当我尝试上面的代码时,我得到:

Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (9): fill

你能帮忙吗? 谢谢, 藤本植物

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这是使用名为 ggstatsplotggplot2 扩展包的一种方法-

    set.seed(123)
    library(tidyverse)
    
    # creating dataframe in long format
    (dat <- read.table(
      text = "Tot_rate   Type1   Type2   Type3
    DPT1 72 50 12 10 
    DPT2 80 30 20 30
    DPT3 92 54 14 24",
      header = TRUE
    ) %>%
      tibble::rownames_to_column(var = "id") %>%
      tidyr::gather(., "key", "counts", Type1:Type3))
    
    #>     id Tot_rate   key counts
    #> 1 DPT1       72 Type1     50
    #> 2 DPT2       80 Type1     30
    #> 3 DPT3       92 Type1     54
    #> 4 DPT1       72 Type2     12
    #> 5 DPT2       80 Type2     20
    #> 6 DPT3       92 Type2     14
    #> 7 DPT1       72 Type3     10
    #> 8 DPT2       80 Type3     30
    #> 9 DPT3       92 Type3     24
    
    # bar plot
    ggstatsplot::ggbarstats(dat,
                            main = id,
                            condition = key,
                            counts = counts,
                            messages = FALSE)
    
    

    reprex package (v0.3.0) 于 2019 年 5 月 27 日创建

    【讨论】:

    • 谢谢!不幸的是,该软件包不适用于我的 R 版本...所以我将等待其他答案
    【解决方案2】:
    library(reshape2)
    
    dat=read.table(text = "Department Tot_rate   Type1   Type2   Type3
    DPT1 72 50 12 10 
    DPT2 80 30 20 30
    DPT3 92 54 14 24", header = TRUE)
    
    
    long_dat <- dat[-2] %>% gather(type,number,Type1:Type3,-c("Department"))
    

    首先,我重塑了您拥有的数据:我将部门放在一个列中,并将您的数据从宽格式重塑为长格式(删除了此处不需要的 tot_rate)。

    p <- ggplot(data=long_dat,aes(x=Department,y=number,fill=type)) +
      geom_bar(position = "fill",stat = "identity")
    
    p
    

    要以百分比为单位缩放条形图,我们使用 geom_barposition 参数设置为 position=fill

    【讨论】:

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