在GGPLOT2传说键更改符号(Changing the symbol in the legend

2019-06-24 02:39发布

如何改变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))

Answer 1:

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



Answer 2:

随着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


文章来源: Changing the symbol in the legend key in ggplot2
标签: r ggplot2 legend