在 ggplot 中编辑图例(文本)标签 [英] Editing legend (text) labels in ggplot

查看:44
本文介绍了在 ggplot 中编辑图例(文本)标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have spent hours looking in the documentation and on StackOverflow, but no solution seems to solve my problem. When using ggplot I can't get the right text in the legend, even though it's in my dataframe. I have tried scale_colour_manual, scale_fill_manual with different values for labels= such as 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")

非常感谢您的帮助!

推荐答案

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

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

您的数据示例:

# 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
", x = "TY [°C]", y = "Txxx", color = "Legend Title
") +
  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"))

这导致:

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

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

这篇关于在 ggplot 中编辑图例(文本)标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆