如何更改ggplot2中的图例线型? [英] How can I change the legend linetype in ggplot2?

查看:197
本文介绍了如何更改ggplot2中的图例线型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的图,其中无法使用scale_linetype_manual根据图中的线型更改图例中的线型.

I have this simple plot where I cannot change the linetype in the legend according to the linetype in the plot using scale_linetype_manual.

生成图的代码是:

library(ggplot2)

x_1 <- rep(0:6, each = 2)
pdf_1 <- c(0,0.05,0.05,0.1,0.1,0.15,0.15,0.3,0.3,0.25,0.25,0.15,0.15,0)

x_2 <- rep(3:9, each = 2)
pdf_2 <- c(0,0.05,0.05,0.1,0.1,0.15,0.15,0.3,0.3,0.25,0.25,0.15,0.15,0)

data_1 <- data.frame(x_1, pdf_1,x_2,pdf_2)

ggplot()+
  geom_line(data=data_1,aes(x=x_1, y=pdf_1, color="Forecaster_1"),linetype='solid',size=1)+
  geom_line(data=data_1,aes(x=x_2, y=pdf_2, color="Forecaster_2"),linetype='dashed',size=1)+
  labs(x = "x") +
  labs(y = "PDF") +
  scale_colour_manual(values = c('Forecaster_1' = 'cornflowerblue', 'Forecaster_2' = 'coral2')) +
  scale_linetype_manual(values = c('Forecaster_1' = 'solid', 'Forecaster_2' = 'dashed')) 

我希望有人帮我解决这个问题.

I would appreciate someone help me with this.

推荐答案

如果将线型映射为aethetic,然后确保两个指南都使用相同的名称,那会更好.例如

It would be better if you mapped the line type as an aethetic and then make sure you use the same name for both guides. For example

ggplot()+
  geom_line(data=data_1,aes(x=x_1, y=pdf_1, color="Forecaster_1", linetype='Forecaster_1'),size=1)+
  geom_line(data=data_1,aes(x=x_2, y=pdf_2, color="Forecaster_2", linetype='Forecaster_2'),size=1)+
  labs(x = "x") +
  labs(y = "PDF") +
  scale_colour_manual("Line", values = c('Forecaster_1' = 'cornflowerblue', 'Forecaster_2' = 'coral2')) +
  scale_linetype_manual("Line", values = c('Forecaster_1' = 'solid', 'Forecaster_2' = 'dashed'))

这篇关于如何更改ggplot2中的图例线型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆