Это потому, что объект place2
, сгенерированный в place2 <- 'AAAAA'
, является чем-то отличным от уровня df2$place
.Обратите внимание, что необходимо другое преобразование.
library(tidyverse)
df <- tibble(place = c("City", "AAAAA", "ZZZZZ", "City", "AAAAA", "ZZZZZ", "City",
"AAAAA", "ZZZZZ"),
x = c(1, 2, 3, 4, 1, 2, 3, 4, 1),
y = c(0.475308283, 0.437369818, 0.204992979, 0.263934572,
0.671616954, 0.955005667, 0.048954328, 0.900494188,
0.418262936))
df2 <- df %>%
filter(place %in% c("City", place2))
levels(df2$place)
> levels(df2$place)
NULL
Итак:
df2 <- df %>%
filter(place %in% c("City", place2)) %>%
dplyr::mutate(place = as.factor(place))
df2
> df2
# A tibble: 6 x 3
place x y
<fct> <dbl> <dbl>
1 City 1 0.475
2 AAAAA 2 0.437
3 City 4 0.264
4 AAAAA 1 0.672
5 City 3 0.0490
6 AAAAA 4 0.900
ggplot(df2, aes(x, y, fill = place)) +
geom_col()
![enter image description here](https://i.stack.imgur.com/D1po7.png)
group_cols2 <- c("City" = "blue", place2 = "green")
place2 <- "AAAAA"
ggplot(df2, aes(x, y, fill = place)) +
geom_col() + scale_fill_manual(values=group_cols2)
![enter image description here](https://i.stack.imgur.com/EmRRX.png)
Чтобы решить эту проблему, есть два простейших способа:
- Изменить цветовую шкалу, как вы уже сделали.
group_cols2 <- c("City" = "blue", "AAAAA" = "green")
ggplot(df2, aes(x, y, fill = place)) +
geom_col() + scale_fill_manual(values=group_cols2)
![enter image description here](https://i.stack.imgur.com/pGiMU.png)
Изменение информации во фрейме данных.
group_cols2 <- c("City" = "blue", place2 = "green")
df2 <- df %>%
filter(place %in% c("City", place2)) %>%
dplyr::mutate(place = as.factor(place),
place = dplyr::case_when(place == "AAAAA" ~ "place2",
place == "City" ~ "City"),
place = forcats::fct_relevel(place, "place2"))
ggplot(df2, aes(x, y, fill = place)) +
geom_col() + scale_fill_manual(values=group_cols2)
![enter image description here](https://i.stack.imgur.com/gF11i.png)