带线型的R ggplot2图例

彼得5

我对R比较陌生,并且在ggplot2上遇到了一些困难。我有由三个变量的数据帧(alphabetagamma),我要绘制在一起。我得到了情节,但有两个问题:

  1. 传说不在情节中,我希望它在情节中
  2. 线型更改为“实线”,“虚线”和“虚线”!

任何想法/建议都将受到欢迎!

p <- ggplot() + 
  geom_line(data=my.data,aes(x = time, y = alpha,linetype = 'dashed')) +
  geom_line(data=my.data,aes(x = time, y = beta, linetype = 'dotdash')) +
  geom_line(data=my.data,aes(x = time, y = gamma,linetype = 'twodash')) +
  scale_linetype_discrete(name = "", labels = c("alpha", "beta", "gamma"))+
  theme_bw()+
  xlab('time (years)')+
  ylab('Mean optimal paths')
print(p)
Vertho

如果您首先将数据重新排列为长格式,并且每行观察一次,则更容易实现目标。

您可以使用tidyr的gather功能进行此操作然后,您可以简单地将线型映射到variable数据中的。

在您的原始方法中,您尝试使用来分配字面量的“线型” aes(),但是ggplot像您所说的那样对此进行解释:“在此处分配线型,就像映射到线型的变量的值为dash / dotdash / twodash一样。” 绘制图时,它会在默认的scale_linetype_discrete中查找线型,其前三个值恰好是实线,点线和虚线,这就是为什么看到混乱的替换项的原因。您可以使用来指定线型scale_linetype_manual

图例的位置可在中调整theme()legend.position = c(0,1)定义要放置在左上角的图例。legend.justification = c(0,1)设置要用于legend.position图例框左上角的锚点

library(tidyr)
library(ggplot2)

# Create some example data
my.data <- data.frame(
    time=1:100,
    alpha = rnorm(100),
    beta = rnorm(100),
    gamma = rnorm(100)
)

my.data <- my.data %>%
    gather(key="variable", value="value", alpha, beta, gamma)

p <- ggplot(data=my.data, aes(x=time, y=value, linetype=variable)) + 
  geom_line() +
  scale_linetype_manual(
    values=c("solid", "dotdash", "twodash"), 
    name = "", 
    labels = c("alpha", "beta", "gamma")) +
  xlab('time (years)')+
  ylab('Mean optimal paths') +
  theme_bw() +
  theme(legend.position=c(0.1, 0.9), legend.justification=c(0,1))
print(p)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章