在ggplot2中更改图例键中的符号

时间:2012-05-01 23:38:22

标签: r ggplot2 legend

如何更改geom_text图例符号?在下面的示例中,我想将图例键中的符号从小写“a”更改为,例如,大写“N”。我看了一个做something similar here的例子,但是无法让这个例子起作用。

# Some toy data
df <- expand.grid(x = factor(seq(1:5)), y = factor(seq(1:5)), KEEP.OUT.ATTRS = FALSE)
df$Count = seq(1:25)

# An example plot
library(ggplot2)
ggplot(data = df, aes( x = x, y = y, label = Count, size = Count)) + 
   geom_text() +
   scale_size(range = c(2, 10))

enter image description here

2 个答案:

答案 0 :(得分:10)

编辑:更新ggplot版本0.9.2

最初的答案(见下文)突破了0.9.0或0.9.1版本。以下内容适用于0.9.2

# Some toy data
df <- expand.grid(x = factor(seq(1:5)), y = factor(seq(1:5)), KEEP.OUT.ATTRS = FALSE)
df$Count = seq(1:25)

# A plot
library(ggplot2)
p = ggplot(data = df, aes( x = x, y = y, label = Count, size = Count)) + 
   geom_point(colour = NA) +
   geom_text(show.legend = FALSE) +  
   guides(size = guide_legend(override.aes = list(colour = "black", shape = utf8ToInt("N")))) +
   scale_size(range = c(2, 10))

p

原始回答 回答我自己的问题并使用上面@ kohske评论中的代码片段:

# Some toy data
df <- expand.grid(x = factor(seq(1:5)), y = factor(seq(1:5)), KEEP.OUT.ATTRS = FALSE)
df$Count = seq(1:25)

# A plot
library(ggplot2)
p = ggplot(data = df, aes( x = x, y = y, label = Count, size = Count)) + 
    geom_text() +
    scale_size(range = c(2, 10))
p

library(grid)
grid.gedit("^key-[-0-9]+$", label = "N")

enter image description here

答案 1 :(得分:3)

安装了gtable版本0.2.0(ggplot2 v 2.1.0)后,可以使用Kohske的原始解决方案(请参阅注释)。

# Some toy data
df <- expand.grid(x = factor(seq(1:5)), y = factor(seq(1:5)), KEEP.OUT.ATTRS = FALSE)
df$Count = seq(1:25)

# Load packages
library(ggplot2)
library(grid)

# A plot
p = ggplot(data = df, aes( x = x, y = y, label = Count, size = Count)) + 
    geom_text() +
    scale_size(range = c(2, 10))
p

grid.ls(grid.force()) 
grid.gedit("key-[-0-9]-1-1", label = "N")

或者,处理grob对象:

# Get the ggplot grob
gp = ggplotGrob(p)
grid.ls(grid.force(gp)) 

# Edit the grob
gp = editGrob(grid.force(gp), gPath("key-[1-9]-1-1"), grep = TRUE, global = TRUE,  
         label = "N")

# Draw it
grid.newpage()
grid.draw(gp)

另一个选项

修改geom

# Some toy data
df <- expand.grid(x = factor(seq(1:5)), y = factor(seq(1:5)), KEEP.OUT.ATTRS = FALSE)
df$Count = seq(1:25)

# Load packages
library(ggplot2)
library(grid)

# A plot
p = ggplot(data = df, aes( x = x, y = y, label = Count, size = Count)) + 
    geom_text() +
    scale_size(range = c(2, 10))
p

GeomText$draw_key <- function (data, params, size) { 
   pointsGrob(0.5, 0.5, pch = "N", 
   gp = gpar(col = alpha(data$colour, data$alpha), 
   fontsize = data$size * .pt)) }

p