簡體   English   中英

在 ggplot 中編輯圖例(文本)標簽

[英]Editing legend (text) labels in ggplot

我花了幾個小時查看文檔和 StackOverflow,但似乎沒有解決方案可以解決我的問題。 使用ggplot我無法在圖例中獲得正確的文本,即使它在我的數據框中。 我已經嘗試了scale_colour_manualscale_fill_manuallabels=不同的值,例如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包創建繪圖的極好資源。

您的數據示例:

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

這導致:

在此處輸入圖片說明

正如@user2739472 在評論中提到的:如果您只想更改圖例文本標簽而不是 ggplot 默認調色板中的顏色,您可以使用scale_color_hue(labels = c("T999", "T888"))而不是scale_color_manual()

圖例標題可以用特定的審美來標記。

這可以使用ggplot2guides()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")

在此處輸入圖片說明

使用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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM