控制geom_text_repel的颜色

时间:2018-04-03 05:27:08

标签: r ggplot2 aesthetics ggrepel

我想将其中一个ggrepel标签的颜色更改为黑色。我试图通过指定...geom_text_repel(...colour='black')来覆盖继承,但这似乎不起作用。

uempmed is blue but I need it to match the black line colour

我尝试解决问题的方法是在第二个geom_text_repel函数中(下面)。

N.B。如果有办法控制单个geom_text_repel元素的颜色,而不是必须两次调用该函数,我宁愿这样做。

library("tidyverse")
library("ggthemes")
library("ggrepel")

df1 <- gather(economics, variable_name, observation, -date) %>% 
  rename(period = date) %>% 
  filter(variable_name == 'psavert')

df2 <- gather(economics, variable_name, observation, -date) %>% 
  rename(period = date) %>% 
  filter(variable_name == 'uempmed')

ggplot(df1, aes(x = period, y = observation, colour = variable_name)) +
  geom_line() +
  geom_line(data = df2, colour = 'black', size = .8) +
  geom_text_repel(
    data = subset(df1, period == max(as.Date(period, "%Y-%m-%d"))),
    aes(label = variable_name),
    size = 3,
    nudge_x = 45,
    segment.color = 'grey80'
  ) +
  geom_text_repel(
    data = subset(df2, period == max(as.Date(period, "%Y-%m-%d"))),
    aes(label = variable_name, colour = 'black'), #How do I set the colour of the label text to black?
    size = 3,
    nudge_x = 45,
    segment.color = 'grey80'
  ) +
  scale_y_continuous(labels = scales::comma) +
  theme_minimal(base_size = 16) +
  scale_color_tableau() + 
  scale_fill_tableau() +
  theme(legend.position = 'none') +
  labs(x="", y="", title = "Economic Data") + 
  scale_x_date(limits = c(min(df1$period), max(df1$period) + 1200))

1 个答案:

答案 0 :(得分:2)

geom_line()图层中执行相同的操作。您想要设置颜色,而不是映射。将colour = 'black'作为geom_text_repel()的参数,而不是aes()

ggplot(df1, aes(x = period, y = observation, colour = variable_name)) +
  geom_line() +
  geom_line(data = df2, colour = 'black', size = .8) + # just like this layer
  geom_text_repel(
    data = subset(df1, period == max(as.Date(period, "%Y-%m-%d"))),
    aes(label = variable_name),
    size = 3,
    nudge_x = 45,
    segment.color = 'grey80'
  ) +
  geom_text_repel(
    data = subset(df2, period == max(as.Date(period, "%Y-%m-%d"))),
    aes(label = variable_name) # don't assign it here, 
    size = 3,
    nudge_x = 45,
    segment.color = 'grey80',
    colour = "black" # assign it here
  ) +
  scale_y_continuous(labels = scales::comma) +
  theme_minimal(base_size = 16) +
  scale_color_tableau() + 
  scale_fill_tableau() +
  theme(legend.position = 'none') +
  labs(x="", y="", title = "Economic Data") + 
  scale_x_date(limits = c(min(df1$period), max(df1$period) + 1200))

请注意,现在第一行AND文本现在都手动设置为"black",因此自动变量赋值将从下一行(和文本)重新开始。如果要手动将其设置为其他颜色,可以使用相同的策略(将其设置为geom的参数,而不是aes的参数

enter image description here