R语言 使用ggplot仅更改一个堆叠条形图的颜色

enyaitl3  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(124)

我有一个堆叠的条形图,用R(markdown)的ggplot。我希望“北”的堆叠条为灰度,其他条保持当前的色标。我实际上使用的是更大的数据集,所以解决方案最好能找到x =“北”的位置,灰度只有那个条。

Region <- c("north", "south", "east", "west", "north", "south", "east", "west")
q14 <- c("5", "5", "5", "5", "4", "4", "4", "4")
N <- c(4342, 5325, 654, 1231, 3453, 234, 345, 5634)
Percentage <- c(72, 71, 68, 67, 21, 20, 18, 17)
df <- data.frame(Region, q14, N, Percentage)

ggplot(df, aes(x=Region, y = Percentage, fill = q14, label = Percentage)) + 
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("#bbd6ad", "#63ab41"))

超级感谢帮助!
我试过调整scale_fill_manual,但没有任何好的结果,只会改变所有条形的颜色。

qojgxg4l

qojgxg4l1#

可能是以下内容

Region <- c("north", "south", "east", "west", "north", "south", "east", "west")
q14 <- c("5", "5", "5", "5", "4", "4", "4", "4")
N <- c(4342, 5325, 654, 1231, 3453, 234, 345, 5634)
Percentage <- c(72, 71, 68, 67, 21, 20, 18, 17)
df <- data.frame(Region, q14, N, Percentage)

df <- mutate(df,
  q14 = case_when(
    Region == "north" &
      q14 == 4 ~ "4 North",
    Region == "north" ~ "5 North",
    q14 == 4 ~ "4",
    TRUE ~ "5"
  )
)

ggplot(df, aes(
  x = Region, y = Percentage,
  fill = q14,
  label = Percentage
)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(
    values =
      c(
        "4 North" = "#444444",
        "5 North" = "#AAAAAA",
        "4" = "#63ab41",
        "5" = "#bbd6ad"
      )
  )

相关问题