情节和图例中的线型不匹配

时间:2017-08-24 11:46:09

标签: r ggplot2 legend facet-wrap

我使用以下代码

绘制此data
df = read.csv(file = "data.csv");
p = ggplot(data = df) + geom_line(aes(x=x,y=yp,linetype="dashed")) + 
geom_line(aes(x=x,y=yi,linetype="solid")) + facet_wrap(~s) + labs(y="y");

我收到了以下plot

代码表示使用yp变量绘制虚线并使用yi变量绘制实线。但是我们在情节中看到的是另一种方式(如果你看一下数据)。图例中的线型也不匹配。有没有办法纠正这个?

2 个答案:

答案 0 :(得分:1)

如上所述,您只需要在linetype函数内修改geom_line的展示位置。

进一步添加图例和颜色以区分yp和yi,请使用:

p = ggplot(data = df) + geom_line(aes(x=x,y=yp,colour="darkblue"), linetype="dotted", show.legend = TRUE) + 
+     geom_line(aes(x=x,y=yi,colour="red"), linetype="solid", show.legend = TRUE) + facet_wrap(~s) + labs(y="y") +scale_color_discrete(name = "Y series", labels = c("yp", "yi"))

<强>结果 snap1

答案 1 :(得分:1)

以下是另一种解决方案:

library(reshape2)
library(ggplot2)

data <- structure(list(x = c(0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L), yp = c(0.469718933105469, 
                                                                     0.00809860229492188, 0.469718933105469, 0.041229248046875, 0.469718933105469, 
                                                                     0.12957763671875, 0.469718933105469, 0.284187316894531), yi = c(0.00809860229492188, 
                                                                                                                                     0.0212535858154297, 0.041229248046875, 0.1033935546875, 0.12957763671875, 
                                                                                                                                     0.28466796875, 0.284187316894531, 0.469718933105469), s = c("q1", 
                                                                                                                                                                                                 "q1", "q2", "q2", "q3", "q3", "q4", "q4")), .Names = c("x", "yp", 
                                                                                                                                                                                                                                                        "yi", "s"), row.names = c(NA, -8L), class = c("tbl_df", "tbl", 
                                                                                                                                                                                                                                                                                                      "data.frame"))
data <-  melt(data,id=c("x","s"))

ggplot(data,aes(x=x,y=value,linetype=variable)) + geom_line() + scale_linetype_discrete(labels=c("solid","dashed")) + facet_wrap(~s)

起初我在reshape2包的帮助下融化了数据,并在ggplot()中进一步使用了它。我也使用了scale_linetype_discrete(),它有一个参数labels =来将图例文本更改为实线和虚线,而不是yp和yi。

enter image description here

相关问题