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

8
这段R代码生成一个ggplot2图表,其中图例键包含以红色、蓝色和绿色重复出现的字母"a"。
x <- rnorm(9); y <- rnorm(9); s <- rep(c("F","G","K"), each = 3)
df <- data.frame(x, y, s)

require(ggplot2)
ggplot(df, aes(x = x, y = y, col = s, label = s)) + 
geom_text() +
scale_colour_discrete(name = "My name", breaks = c("F","K","G"), labels = c("Fbig","Kbig","Gbig")) 

我希望在图例中用“F”、“K”和“G”来代替重复出现的“a”,请问这个有可能吗?谢谢。

2个回答

11

修改代码以适应这个答案: 思路是禁用geom_text图例,但是允许geom_point的图例,但将点大小设置为零以使点在图中不可见,然后在guides语句中设置图例中点的大小和形状。

x <- rnorm(9); y <- rnorm(9); s <- rep(c("F","G","K"), each = 3)
df <- data.frame(x, y, s)
#
require(ggplot2)
#
ggplot(df, aes(x = x, y = y, colour = s, label = s)) +
   geom_point(size = 0, stroke = 0) +  # OR  geom_point(shape = "") +
   geom_text(show.legend = FALSE) +
   guides(colour = guide_legend(override.aes = list(size = 5, shape = c(utf8ToInt("F"), utf8ToInt("K"), utf8ToInt("G"))))) +
   scale_colour_discrete(name = "My name", breaks = c("F","K","G"), labels = c("Fbig","Kbig","Gbig")) 

输入图像说明


1
非常感谢 @Sandy。这正是我想要的。我自己永远也无法解决这个问题。 - Julian Stander

0

手动重命名图例添加

+ scale_x_continuous(breaks=c(x1,x2,x3), labels=c("F", "K", "G"))

其中 x1、x2 和 x3 是点的编号


非常感谢。不幸的是,我无法让它完成工作。定义图例键的符号是带有字母“a”的小灰色框,每个框都有不同颜色的“a”。我想能够指定自己的字母而不是“a”。 - Julian Stander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接