编辑ggplot中的图例(文本)标签

use*_*161 108 text label r ggplot2

我花了几个小时查看文档和StackOverflow,但没有解决方案似乎解决了我的问题.使用时ggplot我无法在图例中获得正确的文本,即使它在我的数据框中.我曾尝试scale_colour_manual,scale_fill_manual对不同的值labels=,例如c("T999", "T888")", "cols".

这是我的代码:

T999 <- runif(10, 100, 200)
T888 <- runif(10, 200, 300)
TY <- runif(10, 20, 30)
df <- data.frame(T999, T888, TY)


ggplot(data = df, aes(x=T999, y=TY, pointtype="T999")) + 
       geom_point(size = 15, colour = "darkblue") + 
       geom_point(data = df, aes(x=T888, y=TY), colour = 'red', size = 10 ) + 
       theme(axis.text.x = element_text(size = 20), axis.title.x =element_text(size = 20),   axis.text.y = element_text(size = 20)) +
       xlab("Txxx") + ylab("TY [°C]") + labs(title="temperatures", size = 15) + 
       scale_colour_manual(labels = c("T999", "T888"), values = c("darkblue", "red")) +    theme(legend.position="topright")
Run Code Online (Sandbox Code Playgroud)

帮助将非常感谢!谢谢.

Jaa*_*aap 118

@Henrik提到的教程是学习如何使用ggplot2包创建绘图的极好资源.

您的数据示例:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
Run Code Online (Sandbox Code Playgroud)

这导致:

在此输入图像描述

正如@ user2739472在评论中所提到的:如果您只想更改图例文本标签而不是ggplot默认调色板中的颜色,则可以使用scale_color_hue(labels = c("T999", "T888"))而不是scale_color_manual().

  • 如果您只想更改图例文本标签而不是ggplot默认调色板中的颜色,可以使用`scale_color_hue(labels = c("T999","T888"))`而不是`scale_color_manual()` (8认同)

Meg*_*ron 32

图例标题可以通过特定的美学来标记.

这可以使用guides()labs()来自ggplot2(更多此处此处)来实现.它允许您使用美学映射添加指南/图例属性.

以下是使用mtcars数据集的示例labs():

ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
  geom_point() +
  labs(x="miles per gallon", y="displacement", size="horsepower", 
       col="# of cylinders", shape="# of gears")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

使用guides()以下方法回答OP的问题:

# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")

# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
  geom_point(size=5) +
  labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  guides(color=guide_legend("my title"))  # add guide properties by aesthetic
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述