我正在使用ggplot2
创建一个图形,其中为不同组绘制的数据在其线型和颜色上都发生变化。我试图更改图例标签,但是,每次尝试更改标签时,我只能针对一种美学(即颜色或线型)更改标签,这会产生两个图例。当两种美学都映射到同一变量时,是否可以更改图例标签?
这是我的工作数据:
# Generate working data
mydat <- structure(list(message_ineq_high_dum = c(0,0,1,1),
human_message_dum = c(1,0,1,0),
fit = c(65,60,76,66),
lwr = c(62,58,74,63),
upr = c(68,63,79,69),
var2 = structure(c(1L,1L, 2L, 2L),
.Label = c("Low", "High"),
class = c("ordered","factor")),
var1 = structure(c(2L, 1L, 2L, 1L),
.Label = c("Low","High"),
class = c("ordered", "factor"))),
.Names = c("message_ineq_high_dum","human_message_dum",
"fit", "lwr", "upr", "var2",
"var1"),
class = "data.frame",
row.names = c(NA, -4L))
让我们尝试绘制数据。在此图中,图例标签为“高”和“低”。
# Plot: incorrect legend labels
library(ggplot2)
ggplot2::ggplot(data = mydat,
aes(x = var2,
y = fit,
group = var1)) +
theme_minimal() +
geom_point(aes(color = var1)) +
geom_line(aes(color = var1, linetype = var1)) +
geom_errorbar(aes(ymin = lwr,
ymax = upr,
width = 0.1,
color = var1,
linetype = var1)) +
labs(x = "var2", y = "var1", color = "var3", linetype = "var3") +
theme(panel.grid.minor = element_blank()) +
scale_color_manual(values = c("Low" = "black", "High" = "red")) +
theme(legend.position="bottom", legend.title = element_blank())
我试图将图例标签从“高”和“低”更改为“ Foo”和“ Bar”,而不进行任何其他更改。我尝试的每种方法都会更改图例标签,同时还要更改(a)图例数量和/或(b)与图例标签相对应的线型/颜色。
答案 0 :(得分:1)
您可以使用scale_linetype_manual
,但不要忘记设置相同的标签!
library(ggplot2)
ggplot2::ggplot(data = mydat,
aes(x = var2,
y = fit,
group = var1)) +
theme_minimal() +
geom_point(aes(color = var1)) +
geom_line(aes(color = var1, linetype = var1)) +
geom_errorbar(aes(ymin = lwr,
ymax = upr,
width = 0.1,
color = var1,
linetype = var1)) +
labs(x = "var2", y = "var1", color = "var3", linetype = "var3") +
theme(panel.grid.minor = element_blank()) +
scale_colour_manual(labels = c("Foo", "Bar"), values = c("black", "red")) +
scale_linetype_manual( labels = c("Foo", "Bar"),values = c("solid", "dashed") ) +
theme(legend.position="bottom", legend.title = element_blank())