首页 > 解决方案 > 无法按线型在 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"))

在此处输入图像描述

标签: rggplot2

解决方案


谢谢@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"))

在此处输入图像描述


推荐阅读