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

时间:2021-06-07 14:59:33

This R code produces a ggplot2 graph in which the legend key contains the letter "a" repeated in red, blue and green.

这个R代码生成一个ggplot2图,其中的legend键包含以红色、蓝色和绿色重复的字母“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")) 

I would like to replace the repeated "a" in the legend key with "F", "K" and "G".

我想把图例键中重复出现的“a”替换为“F”、“K”和“G”。

Is this possible please? Thank you.

这是可能的吗?谢谢你!

2 个解决方案

#1


3  

Adapting code for this answer: The idea is to inhibit the geom_text legend, but to allow a legend for geom_point, but make the point size zero so the points are not visible in the plot, then set size and shape of the points in the legend in the guides statement

为这个答案改编的代码:这个想法是为了阻止地文字的传说,但是允许一个传奇的风水,但是使点大小为零,所以点在情节中是不可见的,然后在向导的声明中设定了传说中的点的大小和形状。

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

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

#2


0  

to manually rename the legend add

手动重命名传奇添加

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

where x1,x2,x3 are the point number

x1 x2 x3是点数吗

#1


3  

Adapting code for this answer: The idea is to inhibit the geom_text legend, but to allow a legend for geom_point, but make the point size zero so the points are not visible in the plot, then set size and shape of the points in the legend in the guides statement

为这个答案改编的代码:这个想法是为了阻止地文字的传说,但是允许一个传奇的风水,但是使点大小为零,所以点在情节中是不可见的,然后在向导的声明中设定了传说中的点的大小和形状。

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

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

#2


0  

to manually rename the legend add

手动重命名传奇添加

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

where x1,x2,x3 are the point number

x1 x2 x3是点数吗