簡體   English   中英

圖例未出現在 ggplot2 條形圖上

[英]Legend Not Appearing on ggplot2 bar plot

鑒於此數據

> vec2df
   vec2  sd
1    9  0.5
2    7  0.2
3    8  0.3
4    9  1.0

和代碼

ggplot(vec2df,
       aes(seq_along(vec2), vec2)) + 
  geom_bar(stat = "identity",
       fill = c("red","blue","green","yellow")) +
  geom_errorbar(aes(ymin = vec2 - sd, ymax = vec2 + sd), 
                width = .2, position = position_dodge(.9), 
                legendPosition="top")

傳說由於某種原因沒有出現。 有人能告訴我如何讓它出現嗎?

因為您沒有將某些變量映射到美學,所以它不會創建圖例。 此外,嘗試使您的x變量成為一個因子,以便將離散的條形映射到離散的顏色而不是漸變。 例如:

# Read data
vec2df <- read.table(textConnection("vec2  sd
1    9  0.5
2    7  0.2
3    8  0.3
4    9  1.0"))

# Plot
ggplot(vec2df,aes(x=as.factor(seq_along(vec2)), y=vec2)) + 
  geom_bar(aes(fill=as.factor(seq_along(vec2))), stat='identity') +
  scale_fill_manual(values=c("red","blue","green","yellow"))

我沒有添加誤差線,但這與問題無關。

在此處輸入圖片說明

暫無
暫無

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

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