繁体   English   中英

如何在ggplot2中获得堆叠geom_bar和geom_point的共同图例?

[英]How to get a common legend for stacked geom_bar and geom_point in ggplot2?

所以我正在构建一个包含以下信息的图表:

  • 单个家庭的收入组成部分(工资、社会转移支付、税收),显示在堆积的 geom_bar 图表中并按国家/地区划分;
  • 每个家庭国家在税收和转移后的净收入,显示在 geom_point 图表中。

这安排在以下数据框中:

example <- data.frame(country = c("Arcadia", "Asgard", "Atlantis", "Avalon"),
            wage = c(80, 70, 55, 40),
            transfers = c(15, 15, 5, 20),
            tax = c(-10, -5, -5, 0),
            net = c(85, 80, 65, 60)) %>% gather(icom, euro, wage:net)

然后绘制成这样:

income_graph <- ggplot(filter(example, icom != "net"), aes(x = country, y = euro, fill = factor(icom, levels = c("transfers", "wage", "tax")))) +
  geom_bar(stat = "identity", colour = "black") +
  geom_point(data = filter(example, icom == "net"), colour = "black", shape = 5) +
  labs(fill = "Income components") +
  scale_fill_brewer(palette = "Greys", labels=(c("Social transfers", "Wage", "Tax"))) 
income_graph 

这导致了下图。

在此处输入图片说明

这就是我需要帮助的地方:该图完成了我需要它做的事情,但我一生都无法弄清楚如何让 geom_bar 和 geom_point 图使用组合图例(即圆形“净”指示器在相同的“收入组成部分”标题下)。 根据我在阅读其他条目时发现的内容,一个解决方案可能是将 geom_bar 和 geom_point 都映射到“fill”,但这似乎最终导致“net”菱形与其他 icom 条目重叠。[*]

提前致谢,并希望这个问题不是重复的——我在 StackOverflow 上找不到适用的解决方案,但如果答案很明显,我很乐意将其重定向到一个。

LS

[*] =(另外,在更小的范围内,是否可以将“净”指标填充为白色并带有黑色轮廓?这可能有一个合乎逻辑的解决方案,但我发现自己对此感到抓耳挠腮。 )

我将填充美学移到了栏,通过将它留在 ggplot 调用中,它试图将其应用于所有几何图形。 我在 geom_point 调用中添加了一种美学,将形状映射到 icom 列,并在稍后使用 scale_shape_manual 进行映射。

希望这就是你想要的!

income_graph <- ggplot(filter(example, icom != "net"),
                       aes(x = country, y = euro)) +
  geom_bar(aes(fill = factor(icom, levels = c("transfers", "wage", "tax"))),
           stat = "identity", colour = "black") +
  geom_point(data = filter(example, icom == "net"),
             aes(shape = icom),
             colour = "black") +
  labs(fill = "Income components", shape = "") +
  guides(shape = guide_legend(order = 2),
         fill = guide_legend(order = 1)) +
  scale_fill_brewer(palette = "Greys", labels=(c("Social transfers", "Wage", "Tax"))) +
  scale_shape_manual(values = c("net" = 5), labels="Net")
income_graph

阴谋

geom_point(shape=21) + scale_color_manual是这种情况的geom_point(shape=21) + scale_color_manual

income_graph <- ggplot(filter(example, icom != "net"), aes(x = country,
 y = euro, fill = factor(icom, levels = c("transfers", "wage", "tax",'net')))) +
  geom_bar(stat = "identity", colour = "black") +
  geom_point(data = filter(example, icom == "net"),aes(color=icom), 
  shape = 21, size = 1.5, stroke = 1,fill='white') +
  labs(fill = "Income components") +
  scale_fill_brewer(palette = "Greys", labels=(c("Social transfers", "Wage", "Tax"))) +
  scale_colour_manual("", values='black', label='Net')
income_graph 

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM