r - 无法按线型在 ggplot2 图例中分配自定义名称和样式
问题描述
简单问题:如何同时为不同绘图的线型分配自定义名称和样式并打印图例。
所有地块都使用library(ggplot2)
.
示例 1:我可以指定我喜欢的线型并根据颜色绘制图例。
ggplot() +
geom_line(data=data.frame(x=c(0, xv[1]), y=c(0, 1)), aes(x=x, y=y, color = "this one should be dashed"), linetype = "dashed")+
geom_line(data=data.frame(x=c(0, xv[2]), y=c(0, 1)), aes(x=x, y=y, color = "this one should be twodash"), linetype = "twodash")+
geom_line(data=data.frame(x=c(0, xv[3]), y=c(0, 1)), aes(x=x, y=y, color = "this one should be dotted"), linetype = "dotted")+
guides(color = guide_legend("by color"))
示例 2:我可以指定我喜欢的线型,但是当我尝试根据线型绘制图例时,没有显示图例。
ggplot() +
geom_line(data=data.frame(x=c(0, 10), y=c(0, 1)), aes(x=x, y=y, linetype = "this one should be dashed"), linetype = "dashed")+
geom_line(data=data.frame(x=c(0, 20), y=c(0, 1)), aes(x=x, y=y, linetype = "this one should be twodash"), linetype = "twodash")+
geom_line(data=data.frame(x=c(0, 30), y=c(0, 1)), aes(x=x, y=y, linetype = "this one should be dotted"), linetype = "dotted")+
guides(linetype = guide_legend("by linetype"))
示例 3:如果我使用默认线型而不指定我的首选类型,我可以按线型绘制图例就好了
ggplot() +
geom_line(data=data.frame(x=c(0, 10), y=c(0, 1)), aes(x=x, y=y, linetype = "this one should be dashed"))+
geom_line(data=data.frame(x=c(0, 20), y=c(0, 1)), aes(x=x, y=y, linetype = "this one should be twodash"))+
geom_line(data=data.frame(x=c(0, 30), y=c(0, 1)), aes(x=x, y=y, linetype = "this one should be dotted"))+
guides(linetype = guide_legend("by linetype"))
解决方案
谢谢@MrFlick。我显然做错了,需要使用scale_linetype_manual()
为线型分配自定义顺序。
ggplot() +
geom_line(data=data.frame(x=c(0, 10), y=c(0, 1)), aes(x=x, y=y, color = "same group", linetype = "A is dashed")) +
geom_line(data=data.frame(x=c(0, 20), y=c(0, 1)), aes(x=x, y=y, color = "same group", linetype = "B is twodash")) +
geom_line(data=data.frame(x=c(0, 30), y=c(0, 1)), aes(x=x, y=y, color = "another group", linetype = "C is solid")) +
scale_linetype_manual(values=c("dashed","twodash","solid")) +
guides(linetype = guide_legend("by linetype")) +
guides(color = guide_legend("by color"))
推荐阅读
- reactjs - 如何在我的 React 应用程序中修复此语法错误?
- php - 如何使用灯箱或其他可以放大图像的插件
- reactjs - AWS Route53 子域重定向设计
- html - jsx根据大小删除父级
- bluetooth - 蓝牙设备不显示串口号
- google-apps-script - 如何隐藏 Google 表单上的设置?
- autodesk-forge - 如何在 Forge 查看器中的 AEC 模型的 2D 图纸空间坐标和世界 3D 坐标之间进行转换?
- node.js - 如何从 UseInterceptors Decorator 获取处理错误
- javascript - 映射包含另一个带有对象的数组的数组并将它们显示在 javascript 的表中
- jmeter - 云系统上的 JMeter 对网关的支付请求失败