更改ggplot2中图例键中的符号

时间:2015-02-22 14:31:18

标签: r ggplot2

此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 个答案:

答案 0 :(得分:5)

调整this answer的代码: 这个想法是禁止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")) 

enter image description here

答案 1 :(得分:0)

手动重命名图例添加

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

其中x1,x2,x3是点数