簡體   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