ggplot中不同几何的scale_color_manual()

时间:2018-10-08 15:59:16

标签: r ggplot2

library(tidyverse)

delta <- tibble(
  type = c("alpha", "beta", "gamma"), 
  a = rnorm(3, 5), 
  b = rnorm(3, 6)
  ) %>% 
  mutate(delta = abs(a - b)) %>% 
  gather(`a`, `b`, `delta`, key = "letter", value = "value")


ggplot(delta %>% filter(letter != "delta"), aes(type, value, fill = letter)) +
  geom_col(position = "dodge") + 
  geom_col(data = delta %>% filter(letter == "delta"), width = 0.5) + 
  scale_color_manual("grey", "black", "blue")

我希望ab条为灰色和黑色。 delta栏变为蓝色。如何使用scale_color_manual()执行此操作?看来我上面的语法已关闭。

enter image description here

1 个答案:

答案 0 :(得分:6)

有两件事需要更改:

  1. 由于您使用过fill = letter,因此您应该使用scale_fill_manual而不是scale_color_manual(如果您使用color = letter会比较合适)。 / p>

  2. 手动颜色values应作为向量提供。

library(tidyverse)

delta <- tibble(
  type = c("alpha", "beta", "gamma"), 
  a = rnorm(3, 5), 
  b = rnorm(3, 6)
) %>% 
  mutate(delta = abs(a - b)) %>% 
  gather(`a`, `b`, `delta`, key = "letter", value = "value")


ggplot(delta %>% filter(letter != "delta"), aes(type, value, fill = letter)) +
  geom_col(position = "dodge") + 
  geom_col(data = delta %>% filter(letter == "delta"), width = 0.5) + 
  scale_fill_manual(values = c("grey", "black", "blue"))

reprex package(v0.2.1)于2018-10-08创建