首页 文章

R:具有n个组的条形图,其堆叠2个值

提问于
浏览
0

我需要生成 barplot ,其中包含以下内容:

I have a csv file with columns: Category Reason Time Value

  • 类别有7个可能的名字(c1 ... c7)

  • Reason有8个可能的名字(n1 ... n8)

  • 时间有2个可能的名字(T1,T2)

  • 值是时间值

示例数据集:

Category    Reason  Time    Value
C1  R1  T1  1
C2  R1  T2  2
C1  R2  T1  3
C2  R2  T2  4
C1  R3  T1  8
C2  R3  T2  0

What i want to achieve: 一个条形图,由3组(即每个REASON一组)组成,其中每组由2个堆叠条组成(即每个CATEGORY的条形图),其中每个条形图描绘其顶部的T1和T2 .

我想我需要类似于R: bar plot with two groups, of which one is stacked的东西,但不幸的是我对R来说很新 .

Similar to this picture, which has in terms of my example:

  • 5个类别

  • 3个理由

  • 4倍的值

  • %作为时间值

Example

任何帮助表示赞赏 .

2 回答

  • 0

    我将向您介绍R中的 ggplot 包,它可以为您提供更好的可视化问题的方法 . 即使它无法解决您当前的问题, ggplot 也是最容易在R中开始可视化的方法 .

    首先是代码:

    library 将加载 ggplotscales

    library(ggplot2)
    library(scales)
    

    生成虚拟数据集

    df = expand.grid(factor(c("C1","C2","C3","C4","C5","C6","C6","C8")),
                     factor(c("R1","R2","R3","R4","R5","R6","R7")),
                     factor(c("T1","T2")))
    

    在x轴上绘制 Category ,在y轴上绘制 Value ,将 Time 绘制为需要 geom_bar() 的堆积条 . ggplot 可以使用 facets ,而不是在条形图本身上进行分组,从而产生更清晰的结果 . scale_y_continuous() 将您的y轴转换为百分比 .

    ggplot(data = df, aes(x=Reason, y=Value, fill = Time)) + 
      geom_bar(stat='identity') + 
      facet_wrap(~Category) +
      scale_y_continuous(labels = percent) +
      theme(panel.background = element_rect(fill = "white"))
    

    enter image description here

  • 0

    你介意共享.csv文件的某个版本吗?没有它我的猜测看起来像这样......

    p_csv <- read.table(file.csv, header = T, sep = ",")
    
    library(ggplot2)
    #using mtcars 
    ggplot(data = mtcars, aes(x = as.factor(cyl))) +
    geom_bar(aes(fill = as.factor(gear)))
    

    如果我能看到一些测试数据,我很乐意帮助更多:)

    仍然不是100%你正在尝试用时间值做什么,但这可能就足够了 . 我稍微调整了您的样本数据,因此时间和类别并不总是同步 .

    df <- data.frame("category" = c("C1", "C2", "C1", "C2", "C1", "C2"),
                 "reason" = c("R1", "R1", "R2", "R2", "R3", "R3"),
                 "time" = c("T1", "T1", "T1", "T2", "T2", "T2"),
                 "value" = c(1,2,3,4,8,0))
    
    ggplot(data = df, aes(x = as.factor(reason), y = value)) +
    geom_bar(aes(fill = as.factor(category)), stat = "identity") +
    facet_grid(~time)
    

相关问题