ggplot中的多个轴标题中的颜色 [英] multiple colors in axes titles in ggplot
问题描述
我如何在ggplot中为轴标签设置多种颜色?
How can I have multiple colors for an axes label in ggplot?
作为一个例子,而不是图例,我希望y轴标签是红色和绿色对应于以下图中的不同点:$ b
$ b
As an example, instead of a legend, I would like the y-axis label to be red and green to correspond to the different points in the following plot:
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)")
我知道我可以使用主题控制整个y轴标签的颜色,如下所示:
I know I can control the color of the entire y-axis label using theme as follows:
p <- p + theme(axis.title.y = element_text(color="red"))
但是, MPG(hwy)为深绿色。有没有办法在ggplot中做到这一点?
But, in the plot I want the "MPG (hwy)" to be in dark green. Is there a way to do this in ggplot?
推荐答案
我不认为您应该滥用轴标题作为图例,但您可以在网格级别执行此操作:
I don't think you should abuse an axis title as a legend, but you can do this at the grid level:
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)
当然通过使用适当的颜色变量映射简单地创建图例将是更可取的。
Of course it would be preferable to simply create a legend by using proper mapping of the color variable.
这篇关于ggplot中的多个轴标题中的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!