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

时间:2019-01-17 14:00:52

标签: r ggplot2 dplyr

所以我正在用以下信息构建图:

  • 单个家庭的收入组成部分(工资,社会转移,税收),显示在堆叠的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 

这将导致下图。

enter image description here

这是我需要帮助的地方:图形可以满足我的需求,但是我一生无法弄清楚如何使geom_bar和geom_point图形使用组合图例(即“净”指标在同一“收入成分”标题下)。从我发现阅读其他条目的发现来看,一种解决方案可能是将geom_bar和geom_point都映射为“填充”,但这似乎最终是将“净”菱形与其他icom条目重叠。[*]

在此先感谢您,希望问题不会重复出现-我在StackOverflow上找不到适用的解决方案,但是如果答案很明显,我们很乐意将其重定向到一个解决方案。

LS

[*] =(单独并且以较小的比例,是否可以将“净”指标填充为白色并用黑色轮廓填充?这可能是合乎逻辑的解决方案,但我发现自己挠头在这里。)

2 个答案:

答案 0 :(得分:1)

我通过将填充美学保留在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

Plot

答案 1 :(得分:0)

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 

enter image description here