2012-05-01 71 views
10

如何更改geom_text圖例鍵符號?在下面的例子中,我想將圖例中的符號從小寫字母「a」改爲大寫字母「N」。我已經看過一個做something similar here的例子,但是無法讓這個例子工作。更改ggplot2中的圖例鍵中的符號

# 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

+5

不幸的是沒有官方的方法。快速入門:'grid.gedit(「^ key - [ - 0-9] + $」,label =「N」)' – kohske

+0

非常感謝。它像一個魅力。 –

+0

無論是你還是@kohske都應該將其作爲答案發布,以便你可以接受它,表明它解決了你的問題。 – joran

回答

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 
9

編輯:更新了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