【问题标题】:Plotting two data series in overlapping barplot (ggplot2)在重叠的条形图中绘制两个数据系列(ggplot2)
【发布时间】:2015-07-09 18:09:41
【问题描述】:

我想在同一个条形图中绘制两个数据系列(相同类型和数量的度量,但在两个时间点测量)。优选地,第一系列以灰色绘制,而第二系列以具有透明度的颜色绘制,使得系列1数据仍然可见。 我拥有的数据格式如下:

MyData = data.frame(
  method=rep(c("A","B","C","D","E"),times=3),
  time1=rnorm(30,10,3),
  time2=rnorm(30,8,2),
  lab=rep(rep(c(1,2,3),each=5),times=2),
  cat=rep(c(1,2),each=15)
  )

为了显示我正在寻找的绘图类型,我在下面添加了用于绘制数据系列 1 的代码:

p <- ggplot(data = MyData,
            aes(x=lab,
                y=time1,
                fill=method))
p + geom_bar(stat="identity",
             position="dodge",
             alpha=.3) +
  facet_grid(. ~ cat)

最后,哪个数据系列是灰色的,哪个是彩色的并不重要,只要它们被绘制在彼此的顶部,并且两者都是可见的。

欢迎所有建议!

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    只能有一个活动的fill_scale,所以我们需要将变量方法映射到其他东西,groupcolor

    library(ggplot2)
    
    MyData = data.frame(
      method=rep(c("A","B","C","D","E"),times=3),
      time1=rnorm(30,10,3),
      time2=rnorm(30,8,2),
      lab=rep(rep(c(1,2,3),each=5),times=2),
      cat=rep(c(1,2),each=15)
    )
    
    p <- ggplot(data = MyData,
                aes(x=lab)) +
      geom_bar(aes(y=time2,fill=method),
               stat="identity",
               position="dodge",
               alpha=.3
               ) +
      geom_bar(aes(y=time1,group=method),
               stat="identity",
               position="dodge",
               alpha=.3) +
      scale_fill_discrete() +
      facet_grid(. ~ cat)
    p
    

    【讨论】:

    • 感谢您的快速回复。但是,正如您在图中看到的那样,这不是我想要的,因为每个图中只有三个灰色条和 15 个彩色条。
    • 我自己也遇到了同样的问题。当fill 设置为“灰色”而不是“方法”(在我的示例中)时,ggplot 不会进行正确的分组,并且每个 x 轴值仅绘制一个(灰色)条。
    • 只需使用group 而不是fillgeom_bar(aes(x=lab, y=time1, group=method), ...)
    • 如果你也使用colour==method,它会更具可读性。在我看来,我仍然认为这是相当具有误导性的情节。
    • @zero323 这实际上是我开始的。我知道意识到我不需要 group 声明然后
    【解决方案2】:

    我一直在考虑添加第二个数据系列的不同方法。我可以使用geom_point 而不是geom_bar 添加第二个系列,因为这样可以减少混乱。但是,如何将点定位在相应的条上? (即现在这些点都在同一个 x 轴位置)。

    library(ggplot2)
    
    MyData = data.frame(
      method=rep(c("A","B","C","D","E"),times=3),
      time1=rnorm(30,10,3),
      time2=rnorm(30,8,2),
      lab=rep(rep(c(1,2,3),each=5),times=2),
      cat=rep(c(1,2),each=15)
    )
    
    p <- ggplot(data = MyData,
                aes(x=lab)) +
      geom_bar(aes(y=time1,fill=method),
               stat="identity",
               position="dodge",
               alpha=.7
      ) +
      geom_point(aes(y=time2,group=method),
               stat="identity",
               position="dodge",
               alpha=.8,
               size=3) +
      scale_fill_brewer(palette=3) +
      facet_grid(. ~ cat)
    p
    

    【讨论】:

      猜你喜欢
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      相关资源
      最近更新 更多