【问题标题】:How to overlay a barplot on a stacked barplot?如何在堆叠的条形图上叠加条形图?
【发布时间】:2021-03-21 17:10:39
【问题描述】:

我正在尝试将条形图覆盖在堆积条形图上,如下图所示。虽然这运作良好,但虚线类型并未在图例中显示。

Dotted bar plot on top of stacked barplot

这是我的数据:

data = data.frame(treat=c("min","plus","min","plus"),
                  obs=c(8,7,121,98),
                  type=c("Tare","Tare","Net","Net"))

data2 = data.frame(treat=c("min","plus"),
                   obs=c(20,15),
                   type=c("Sugar","Sugar"))

以及我用来制作图表的代码:

ggplot(data = data, aes(x=treat, y=obs, fill = type)) + 
  theme_classic() + 
  geom_bar(stat="identity", col = "black", width = .75) +
  geom_bar(data = data2, stat="identity", fill = "transparent", col = "black", size = .8, linetype = "dotted", width = .75, show.legend = F) +
  scale_fill_manual(values = c("#F8766D", "#00BFC4", NA),
         limits = c("Tare", "Net", "Sugar"))

如何使第二个条在图例中显示为虚线?

【问题讨论】:

  • 添加图后我简化了代码,所以图与代码不完全匹配,但我的问题是什么的想法仍然可见
  • 我理解正确吗,你想为虚线有一个单独的图例吗?
  • 不,我希望 'Sugar' 左侧的小方块带有虚线

标签: r ggplot2 overlay geom-bar stacked


【解决方案1】:

这就是你要找的吗?

library(tidyverse)
data = data.frame(treat=c("min","plus","min","plus"),
                  obs=c(8,7,121,98),
                  type=c("Tare","Tare","Net","Net"))

data2 = data.frame(treat=c("min","plus"),
                   obs=c(20,15),
                   type=c("Sugar","Sugar"))

ggplot(data = data, aes(x=treat, y=obs, fill = type)) + 
  theme_classic() + 
  geom_bar(stat="identity", col = "black", width = .75) +
  geom_bar(data = data2, stat="identity", 
           fill = "transparent", col = "black", size = .8, 
           aes(linetype = "dotted"), 
           width = .75, 
           show.legend = T) +
  scale_fill_manual(values = c("#F8766D", "#00BFC4", NA),
                    limits = c("Tare", "Net", "Sugar"),
                    name="type")+
  scale_linetype_manual(name="Sugar", values="dotted")+
  guides(fill = guide_legend(keywidth = 1, keyheight = 1),
         linetype=guide_legend(keywidth = 3, keyheight = 1))

reprex package (v0.3.0) 于 2020 年 12 月 10 日创建

【讨论】:

  • 不完全是,我希望糖前面的小方块带有虚线。如果这不起作用,您的解决方案是次优的
猜你喜欢
  • 2023-01-31
  • 2023-01-21
  • 1970-01-01
  • 2012-05-11
  • 2019-05-30
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多