【问题标题】:How to plot multiple facets histogram with ggplot in r?如何在 r 中使用 ggplot 绘制多个方面直方图?
【发布时间】:2019-05-08 08:30:30
【问题描述】:

我有一个这样的数据框

 Elem. Category. SEZa SEZb SEZc

  A.     ONE.     1.   3.   4
  B.     TWO.     4.   5.   6

我想用 ggplot 在三个不同方面(SEZa、SEZb、SEZc)绘制三个直方图,其中 x 值是类别值(ONE.e TWO.),y 值是 SEZa、SEZb 列中的数字, 经济特区。

类似这样的:

我该怎么办?谢谢你的建议!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    假设df是你的data.frame,我会先从宽格式转换成长格式:

    new_df <- reshape2::melt(df, id.vars = c("Elem", "Category"))
    

    然后使用geom_col() 而不是geom_histogram() 进行绘图,因为您似乎已经预先计算了 y 值并且不需要 ggplot 来为您计算这些值。

    ggplot(new_df, aes(x = Category, y = value, fill = Elem)) +
      geom_col() +
      facet_grid(variable ~ .)
    

    【讨论】:

      【解决方案2】:

      我认为您正在寻找的是这样的:

      library(ggplot2)
      library(reshape2)
      
      df <- data.frame(Category = c("One", "Two"),
                       SEZa = c(1, 4),
                       SEZb = c(3, 5),
                       SEZc = c(4, 6))
      
      df <- melt(df)
      
      ggplot(df, aes(x = Category, y = value)) +
        geom_col(aes(fill = variable)) + 
        facet_grid(variable ~ .)
      

      我的灵感是:

      http://felixfan.github.io/stacking-plots-same-x/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多