简体   繁体   English

ggplot2在图例中显示的线型不正确

[英]Incorrectly displayed linetypes in the legend with ggplot2

I'm following this links example , as I have a similar situation where I'm trying to graph two data frames in the same plot. 我遵循此链接示例 ,因为我有一个相似的情况,我试图在同一图中绘制两个数据框。 I'm only interested in changing the linetypes for one of the data frames, which works in the graph, but doesn't display correctly in the legend. 我只对更改其中一个数据框的线型感兴趣,该数据框可在图形中使用,但在图例中无法正确显示。

Example dataset: 示例数据集:

set.seed(456)
n <- 20
dfr <- data.frame(
  id=rep(1:n, 2),
  group=rep(c("1","2"), each=n), value=c(rnorm(n), rnorm(n, sd=1.1))
)

df_95ci <- data.frame(y_values=c(-1,1)*qnorm(0.95)) 
df_99ci <- data.frame(y_values=c(-1,1)*qnorm(0.99))

require(ggplot2)

Code: 码:

  ggplot(data=dfr, mapping=aes(x=id, y=value)) +
  geom_line(mapping=aes(colour=group)) +
  geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, size= "95% CI"), colour = "orange", linetype="dotdash") +
  geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, size= "99% CI"), colour = "darkred", linetype="dotted") +
  scale_color_hue("Group") +
  scale_size_manual(
    "CI horizontal line", values=rep(1,4),
    guide=guide_legend(override.aes = list(colour=c("orange", "darkred")))
  ) +
  scale_linetype_identity(guide="legend")

Output 产量

As you can see I have two lines with different linetypes, but they're identical in the legend. 如您所见,我有两行具有不同的线型,但是它们在图例中是相同的。

Do you want this? 你想要这个吗?

ggplot(data=dfr, mapping=aes(x=id, y=value)) +
    geom_line(mapping=aes(colour=group)) +
    geom_hline(data= df_95ci, mapping=aes(yintercept=y_values, linetype= "95% CI"), 
               colour = "orange", size = 1) +
    geom_hline(data= df_99ci, mapping=aes(yintercept=y_values, linetype= "99% CI"), 
               colour = "darkred", size = 1) +
    scale_linetype_manual(
        "CI horizontal line", values=c("95% CI" = 4, "99% CI" = 3),
        guide=guide_legend(override.aes = list(colour=c("orange", "darkred")))
    )

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM