【问题标题】:multiple colors in axes titles in ggplotggplot中轴标题中的多种颜色
【发布时间】:2014-08-03 11:30:10
【问题描述】:

如何在 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中做到这一点?

【问题讨论】:

  • 我认为如果不严重滥用ggplot 语法,就无法做到这一点。但也许只是添加一个图例会有所帮助?类似library(reshape2); temp &lt;- melt(mpg[mpg$model=="a4", c("trans", "cty", "hwy")], id.vars = "trans"); ggplot(temp, aes(x = trans, y = value, color = variable)) + geom_point() + scale_colour_manual(values = c("red", "dark green")) + ylab("MPG (city); MPG (hwy)")

标签: r ggplot2


【解决方案1】:

我认为您不应该滥用轴标题作为图例,但您可以在网格级别这样做:

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)

【讨论】:

  • 我收到此错误:Error in set.gpar(x$gp) : argument must be a 'gpar' object。有解决办法吗?
  • 是的,传递一个 gpar 对象。 ggplot2 的内部工作在过去四年中发生了很大变化。
  • 我能问你怎么做吗?我对gpar 不是很自信,我的试验到现在都失败了。
  • 我正在使用 v2.2.1.9000 并且错误仍然存​​在。它没有绘制任何东西
  • 您可能需要检查内部结构现在是什么(请参阅我对str 的评论)。我不会安装开发版。
【解决方案2】:

扩展 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 轴不能标注在右侧呢?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多