【问题标题】:One bar stacked barplot一个条形堆叠条形图
【发布时间】:2014-06-10 10:33:03
【问题描述】:

尽管我已经搜索了网络和可用资源,但我似乎无法完全理解 R 需要堆叠条形图数据的方式。

我有以下数据

    df<-c("III", "III", "I", "I", "I", "II", "I", "I", "I", "I", "I", 
"II", "I", "I", "I", "I", "I", "I", "I", "II", "I", "III", "II", 
"II", "III", "I", "II", "II", "I", "I", "IV", "I", "III", "I", 
"III", "I", "I", "II", "I", "II", "II", "I", "II", "I", "II", 
"II", "II", "II", "I", "I", "II", "I", "I", "I", "I", "I", "I", 
"II", "II", "III", "I", "III", "I", "I", "I", "I", "II", "I", 
"II", "III", "I", "I", "I", "I", "III", "II", "II", "I", "I", 
"II", "I", "II", "III", "II", "III", "II", "III", "I", "III", 
"III")

我想创建一个带有 I、II、III、IV 百分比的单条堆叠条形图。我只能让 R 做以下事情

barplot(table(df)*100/90, col=c("white", "gray70", "gray40", "black"), ylim=c(0,100))

有什么方法可以使这个单条堆叠条形图?请仅使用 baseR 解决方案。 谢谢

【问题讨论】:

    标签: r graph plot


    【解决方案1】:

    这是一个使用ggplot 的解决方案,它不需要数值向量/矩阵作为条形图的输入。

    library(ggplot2)
    ggplot(data.frame(df))+geom_bar(aes(x="df",fill=df),position="stack")
    

    【讨论】:

      【解决方案2】:

      这是一种可能性(灵感来自http://r.789695.n4.nabble.com/How-to-add-marker-in-Stacked-bar-plot-td4635946.html):

      df<-c("III", "III", "I", "I", "I", "II", "I", "I", "I", "I", "I", 
      "II", "I", "I", "I", "I", "I", "I", "I", "II", "I", "III", "II", 
      "II", "III", "I", "II", "II", "I", "I", "IV", "I", "III", "I", 
      "III", "I", "I", "II", "I", "II", "II", "I", "II", "I", "II", 
      "II", "II", "II", "I", "I", "II", "I", "I", "I", "I", "I", "I", 
      "II", "II", "III", "I", "III", "I", "I", "I", "I", "II", "I", 
      "II", "III", "I", "I", "I", "I", "III", "II", "II", "I", "I", 
      "II", "I", "II", "III", "II", "III", "II", "III", "I", "III", 
      "III")
      
      freq <- table(df)
      
      df <- data.frame(names=names(freq), freq=as.vector(freq))
      
      barplot(as.matrix(df[,2]), col=cm.colors(length(df[,2])), legend=df[,1], xlim=c(0,6), width=1) 
      

      【讨论】:

        【解决方案3】:

        以下内容对你有用,但看起来不太好

        barplot(as.matrix(table(df)*100/90), 
                col=c("white", "gray70", "gray40", "black"), 
                ylim=c(0,100))
        

        【讨论】:

        • 谢谢。它工作得很好。条形图理解为堆叠图的 as.matrix 是什么?
        • 它将数据转换为二维,将被barplot解释为多个类别...
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-21
        • 2012-05-11
        • 2023-01-31
        • 2023-04-09
        • 1970-01-01
        相关资源
        最近更新 更多