簡體   English   中英

當我填充ggplot2上的條形時,圖例消失

[英]Legend disappears when I fill the bars on ggplot2

我正在嘗試使用以下代碼繪制多層餅圖

df <- data.frame(a = c(4, 3, 3, 8, 1, 1, 10),
                 b = c("x", "x", "x", "y", "y", "y", "z"),
                 c = c("x1", "x2", "x3", "y1", "y2", "y3", "z1"))

ggplot(df, aes(x = b, y = a, fill = c))+
  geom_bar(stat = "identity",
           color = "black", 
           fill = c("yellow","blue","black","green","red","white","black"))+
  coord_polar(theta="y")

問題是,當我將填充變量添加到geom_bar中時,我失去了圖例,甚至根本無法添加圖例,嘗試按照某些建議添加scale_fill_manual() ,但它仍然對我不起作用,這是為什么發生了什么?

PS:是否可以刪除每個條/圓之間的空間?

您不需要第二個fill參數,即geom_bar中的geom_bar

library(ggplot2)
    df <- data.frame(a = c(4, 3, 3, 8, 1, 1, 10),
                     b = c("x", "x", "x", "y", "y", "y", "z"),
                     c = c("x1", "x2", "x3", "y1", "y2", "y3", "z1")
                     )

    ggplot(df, aes(x = b, y = a, fill = c))+
      geom_bar(stat = "identity",
               width=1,#set width to remove white space, b/c the default is 0.9
               color = "black",)+
      coord_polar(theta="y")+ #Note you don't need the scale_fill_manual below; if omitted, r uses the default palette
      scale_fill_manual(values = c("yellow","blue","black","green","red","white","black"))

    )

結果:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM