ggplot中轴标题中的多种颜色

cfo*_*ser 9 r ggplot2

如何在ggplot中为轴标签设置多种颜色?

作为示例,我希望y轴标签为红色和绿色,而不是图例,而不是图例,以对应下图中的不同点:

p <- ggplot(mpg[mpg$model=="a4",],aes(x=trans,y=cty))+geom_point(color="red")+
     geom_point(aes(y=hwy),color="dark green") +
     ylab("MPG (city); MPG (hwy)")
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用主题控制整个y轴标签的颜色,如下所示:

p <- p + theme(axis.title.y = element_text(color="red"))
Run Code Online (Sandbox Code Playgroud)

但是,在情节中我希望"MPG(hwy)"呈深绿色.有没有办法在ggplot中这样做?

Rol*_*and 11

我不认为您应该将轴标题滥用为图例,但您可以在网格级别执行此操作:

library(ggplot2)

p <- ggplot(mpg[mpg$model=="a4",],aes(x=trans,y=cty))+
  geom_point(color="red")+
  geom_point(aes(y=hwy),color="dark green") +
  ylab("MPG (city); MPG (hwy)")

g <- ggplotGrob(p)

g[[1]][[7]]$label <- c("MPG (city);",  "MPG (hwy)")
g[[1]][[7]]$gp$col <- c("red", "dark green")
library(grid)
g[[1]][[7]]$y <- unit(c(0.45, 0.54), "npc")
#fiddle with the coordinates until the positioning fits for your specific strings

plot(g)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当然,最好通过使用颜色变量的适当映射来简单地创建图例.

更新

使用ggplot2 v2.2.1时,由于gtree已更改,因此需要对其进行调整.现在这个工作:

#g[[1]] shows which grob is the y axis title
#then use str to see the structure of the grop
#you can also use grid.edit instead but I find the following more easy
g[[1]][[13]]$children[[1]]$label <- c("MPG (city);",  "MPG (hwy)")
g[[1]][[13]]$children[[1]]$gp$col <- c("red", "dark green")
g[[1]][[13]]$children[[1]]$hjust <- c(1, 0)
g[[1]][[13]]$children[[1]]$y <- unit(c(0.5, 0.5), "npc")

plot(g)
Run Code Online (Sandbox Code Playgroud)