r - 更改图例标签而不更改图例标记或数量
问题描述
我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())
我正在尝试将图例标签从“High”和“Low”更改为“Foo”和“Bar”而不更改任何其他内容。我尝试过的每种方法都会更改图例标签,同时还会更改(a)图例的数量和/或(b)与图例标签对应的线型/颜色。
解决方案
你范使用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())
推荐阅读
- python - 如何对图像中相同或相似的像素进行分组
- rest - 执行 powershell 时出现 Kudu REST API 命令端点错误
- r - 尝试在 R 中做一个具有特殊性的直方图
- swift - 接口没有定义视图控制器类
- c++ - 使用 scanf 读取文件中的图表时遇到问题
- python - Selenium,Pycharm 不识别 import 语句
- sql - 如果左字段为空,则左连接并使用左字段,否则使用右字段
- curl - 为什么 curl 打印页面的 HTML 代码?
- java - 使用 Java Regex 将包含未知数量匹配项的字符串解析为 List
- javascript - 浏览器更新横幅按钮