'scale_fill_manual not respecting to the order of values and labels
For the code below, I try to use scale_fill_manual('trend', values = c('red', 'blue', 'gray'), labels = c('up', 'down', 'keep')) to set bar color for each month with red for up, blue for down and gray for keep:
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()
)
Now the problem we can find in this figure is: red for down, blue for keep and gray for up, which is different from the requested.
If we comment scale_fill_manual(...) part and rerun the code, the default order correspondence is correct:
So I'm wondering why I get this issue and what's the correct method to set customized colors for this specific data (only one keep entry for September group)? Thanks.
Data:
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


