對于下面的代碼,我嘗試使用for 、for和forscale_fill_manual('trend', values = c('red', 'blue', 'gray'), labels = c('up', 'down', 'keep'))為每個月設定條形顏色:redupbluedowngraykeep
df <- structure(list(month = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L,
4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 9L, 10L, 10L, 11L,
11L, 12L, 12L), .Label = c("1", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "11", "12"), class = "factor"), trend = c("down",
"up", "down", "up", "down", "up", "down", "up", "down", "up",
"down", "up", "down", "up", "down", "up", "down", "keep", "up",
"down", "up", "down", "up", "down", "up"), numbers = c(10L, 16L,
16L, 11L, 15L, 12L, 14L, 13L, 15L, 12L, 15L, 12L, 14L, 13L, 16L,
11L, 14L, 1L, 12L, 15L, 12L, 14L, 13L, 15L, 12L)), class = "data.frame", row.names = c(NA,
-25L))
ggplot(df, aes(x = month, y = numbers))
geom_bar(aes(fill = trend), alpha=0.8,
stat='identity', position = 'dodge', width = 0.7)
scale_fill_manual('trend', values = c('red', 'blue', 'gray'),
labels = c('up', 'down', 'keep'))
geom_text(aes(x = month, y = numbers, label=numbers, group=trend), position = position_dodge(width=0.9), vjust=-0.25)
labs(x='month',
y='numbers')
theme(
legend.position='bottom',
legend.title = element_blank()
)

現在我們可以在這個圖中發現的問題是:redfor down, blueforkeep和grayfor up,這與請求的不同。
如果我們注釋scale_fill_manual(...)部分并重新運行代碼,默認順序對應是正確的:

所以我想知道為什么我會遇到這個問題,以及為這個特定資料設定自定義顏色的正確方法是什么(keep九月組只有一個條目)?謝謝。
資料:
month trend numbers
1 1 down 10
2 1 up 16
3 2 down 16
4 2 up 11
5 3 down 15
6 3 up 12
7 4 down 14
8 4 up 13
9 5 down 15
10 5 up 12
11 6 down 15
12 6 up 12
13 7 down 14
14 7 up 13
15 8 down 16
16 8 up 11
17 9 down 14
18 9 keep 1
19 9 up 12
20 10 down 15
21 10 up 12
22 11 down 14
23 11 up 13
24 12 down 15
25 12 up 12
uj5u.com熱心網友回復:
您可以指定values為命名字符向量scale_fill_manual:
ggplot(df, aes(x = month, y = numbers))
geom_bar(aes(fill = trend), alpha=0.8,
stat='identity', position = 'dodge', width = 0.7)
scale_fill_manual('trend',
values = c(up = 'red', down = 'blue', keep = 'gray'))
geom_text(aes(x = month, y = numbers, label=numbers, group=trend), position = position_dodge(width=0.9), vjust=-0.25)
labs(x='month',
y='numbers')
theme(
legend.position='bottom',
legend.title = element_blank()
)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/436083.html
