【问题标题】:Stacked bar plot from 3-dimension data frame来自 3 维数据框的堆积条形图
【发布时间】:2020-09-27 12:27:37
【问题描述】:

我的数据框(从 .csv 文件加载)如下所示:

我想制作一个看起来像这样的图表(在 excel 中完成):

我试过了:

barplot(t(as.matrix(df)), beside = FALSE, names.arg = df$cause, legend.text = TRUE, ylab = "Average Length (days)", xlab = "Cause")

没用,给了我这个:

我该怎么做?

【问题讨论】:

    标签: r dataframe bar-chart


    【解决方案1】:

    尝试将数据重新整形为长。这里是使用ggplot2tidyverse 函数的解决方案代码:

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    #Data
    df <- data.frame(Cause=c('Cellulitis','Convulsions and epilepsy',
                             'Dental conditions','Ear, nose and throat infections'),
                     under=c(3.7,2,1.2,1.2),
                     over=c(5.4,3.9,1.8,2.5),stringsAsFactors = F)
    #Plot
    df %>% pivot_longer(-Cause) %>%
      ggplot(aes(x=Cause,y=value,fill=name))+
      geom_col(color='black')+
      theme_bw()+
      theme(legend.position = 'top')+
      scale_fill_manual('',values=c('tomato','cornflowerblue'))
    

    输出:

    对于进一步的定制,你可以使用这个:

    #Plot 2
    df %>% pivot_longer(-Cause) %>%
      mutate(name=paste(name,'65')) %>%
      ggplot(aes(x=Cause,y=value,fill=name))+
      geom_col(color='black')+
      theme_bw()+
      theme(legend.position = 'top')+
      scale_fill_manual('',values=c('tomato','cornflowerblue'))
    

    输出:

    【讨论】:

    • 非常感谢您的回复,当我尝试运行绘图代码时,我收到此错误:“错误:cols 必须选择至少一列。”。我是 R 新手,所以不确定是什么原因造成的。
    • @Sam 它必须在pivot_longer() 中,您能否分享str(yourdataframe) 以便查看您的变量名称也尝试加载我在问题开头提到的包。让我知道这是怎么回事!
    • 嗯,当我这样做时,我得到'data.frame': 0 obs. of 0 variables。我的框架一定有问题吧?
    • 是的,看起来没有数据存在。尝试检查数据的结构,看看它是否与我共享的数据相同,这是您的屏幕截图的克隆。让我知道进展情况或邀请我聊天我很乐意帮助meta.stackexchange.com/questions/187426/…
    • 啊,没关系,我让它工作了,在其他地方出现了一个不相关的错误。非常感谢!
    【解决方案2】:

    使用 reshape2 包和 ggplot2 您可以将数据转换为更长的格式,然后使用类型,即 over|under 作为填充。

    library(ggplot2)
    library(reshape2)
    ggplot(data=melt(dt,id.vars="cause"),aes(x=cause, y=value, fill=variable)) + geom_bar(stat="identity")
    

    结果

    数据

    dt <- read.csv(text="cause,under,over
    Cellulitis,3.7,5.4
    Convulsions and epilepsy,2,3.9
    Dental conditions,1.2,1.8
    Ear; nose and throat infections,1.2,2.5")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多