13

如何更改 geom_text 图例键符号?在下面的示例中,我想将图例键中的符号从小写“a”更改为大写“N”。我已经查看了一个在此处执行类似操作的示例,但无法使该示例正常工作。

# 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))

在此处输入图像描述

4

2 回答 2

11

编辑:更新 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")

在此处输入图像描述

于 2012-05-02T06:49:27.053 回答
3

gtable安装0.2.0 ( v 2.1.0) 版本后,可以使Kohskeggplot2的原始解决方案(见评论)工作。

# 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)

另外一个选项

修改几何

# 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
于 2015-10-21T06:49:43.303 回答