我对ggplot2中的图例中的变量名称有疑问
我相信您会发现它很简单,因此我暂时不提供可复制的代码。
我对长数据运行此ggplot2查询:
ggplot(subset(BaumA_long,
Messpunkt %in% c("Tleaf","Tair","Tcrown","TbarkS","TbarkN", "Tsoil")),
aes(x=Zeit, y=value, color=Messpunkt)) +
geom_line(size=0.3) +
scale_x_datetime(limits=start.endKW26, labels = date_format("%d.%m. %H h",tz = "CET"),
breaks = date_breaks("12 hours"), expand = c(0, 0)) +
scale_y_continuous(limits = c(5, 55), breaks = seq(10, 55, by = 3)) +
labs(x="Datum", y="Temperatur") +
ggtitle("Cbet 1")+
theme(plot.title = element_text(vjust=-15),
axis.text.x = element_text(angle = 35))+
theme(legend.position='top') +
#labels=c("Tleaf"="Blatt", "Tair"="Luft", "Tcrown"="Krone",
# "TbarkS"="Borke_S", "TbarkN"="Borke_N","Tsoil"="Substrat") +
scale_color_manual(values = c("Tleaf" = "#339900", "Tair" = "blue", "Tcrown"= "red",
"TbarkS" = "orange2", "TbarkN" = "pink", "Tsoil" = "brown"))
这给了我下面的情节:
我要更改的只是图例中变量“ Tleaf”的名称,依此类推。我尝试过:
ggplot +
labels=c("Tleaf"="Blatt", "Tair"="Luft", "Tcrown"="Krone",
"TbarkS"="Borke_S", "TbarkN"="Borke_N","Tsoil"="Substrat") +
没有成功。
为了保持代码的简洁明了,我想避免重命名所有变量,因为我有很多数据集。
答案 0 :(得分:1)
使用scale_color_discrete()
:
library(ggplot2)
labels <- c(var1 = "Custom Value 1", var2 = "Custom Value 2", var3 = "Custom Value 3")
ggplot(df, aes(x, val, col = var)) +
geom_line() +
scale_color_discrete(labels = labels)
structure(list(x = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L), var = c("var1", "var1", "var1", "var1",
"var1", "var1", "var1", "var1", "var1", "var1", "var2", "var2",
"var2", "var2", "var2", "var2", "var2", "var2", "var2", "var2",
"var3", "var3", "var3", "var3", "var3", "var3", "var3", "var3",
"var3", "var3"), val = c(-0.33, 0.96, 1.39, 0.92, 1.06, -0.63,
-0.33, 2.94, -1.42, -0.15, 3.6, 1.59, 3.87, 3.25, 2.25, 2.83,
2.71, 1.13, 4.49, 0.8, 2.67, 3.22, 3.23, 3.39, 2.92, 3.04, 3,
3.3, 3.22, 3.4)), class = "data.frame", row.names = c(NA, -30L
))