如何添加element_text色标作为图例?

时间:2019-04-22 08:13:43

标签: r ggplot2

我正在尝试创建一个图形,该图形通过比较(与一个值)将x值分组,并且还通过使用矢量对x.axis.text进行颜色缩放。图例仅用于几何图形,但我也想为element_text颜色添加另一个图例。

我尝试了ggplot(data, aes(x = x, y = y, color = a)),但是没有用。

这与我的代码非常相似

#Create data
x <- c("a","b","c","d","e","f")
y <- c("10", "9","-10","11","-3","-15")
data <- data.frame(x, y)
data$y <- as.numeric(as.character(data$y))
data$category <- ifelse(as.numeric(data$y)<10, 0, 1)
data$category <- as.factor(data$category)
a <- ifelse(data$category == 0, "purple", "black")
#Graph
library(ggplot2)

ggplot(data, aes(x = x, y = y)) + 
  geom_bar(stat = "identity", aes(fill = category)) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = a))

是否可以将主题色标添加为图例?

1 个答案:

答案 0 :(得分:1)

也许是这样的

ggplot(data, aes(x = x, y = y)) + 
  geom_bar(stat = "identity", aes(fill = category)) +

  # invisible geom_text layer to trigger generation of legend for text colour
  geom_text(aes(label = y, color = category), alpha = 0) +

  # specify colour mapping accordingly with alpha = 1
  scale_color_manual(values = c("0" = "purple", "1" = "black"),
                     guide = guide_legend(override.aes = list(alpha = 1))) +

  theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = a))

plot