如何在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)")
我知道我可以使用主题控制整个y轴标签的颜色,如下所示:
p <- p + theme(axis.title.y = element_text(color="red"))
但是,在情节中我希望“MPG(hwy)”呈深绿色。有没有办法在ggplot中这样做?
答案 0 :(得分: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)
当然,最好只使用颜色变量的正确映射来创建图例。
使用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)
答案 1 :(得分:3)
扩展David Arenburg的评论,如果没有进入网格级别,这会更加接近:
library(reshape2) # easier to group by color with melted data
temp <- melt(mpg[mpg$model=="a4", c("trans", "cty", "hwy")], id.vars = "trans")
使用相同变量标识的标签字符串进行分组:
labs <- data.frame(variable = c("cty", "hwy"),
value = c("MPG (city); ", "MPG (hwy) "),
y = c(22,26)) # vertical position for labels
p <- ggplot(temp, aes(x=trans, y=value, color=variable)) +
geom_point() +
geom_text(data = labs, angle = 90, # add rotated text near y-axis
aes(x = 0.5, y = y, label = value)) +
scale_color_manual(values=c("red", "dark green"), guide = "none") +
ylab("") # hide default y-axis label
谁说y轴无法在右侧标记?无论如何?