根据值绘制仅在线和仅点的一个变量 [英] Plotting one variable both line-only and points-only, depending on value

查看:37
本文介绍了根据值绘制仅在线和仅点的一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ggplot2在同一张图中绘制3个时间序列.我想将前两个系列绘制为没有点的实线.我想绘制仅包含点而没有线的第三系列.我怎样才能做到这一点?

 库(ggplot2)库(reshape2)d1<-c(1、2、3、2、1、2、3、4、5、6、5、4、3、1)d2 <-c(0、2、4、5、4、3、2、4、6、7、6、5、3、1)d3 <-c(0、1、2、4、4、1、2、3、4、7、8、3、5、0)ts1<-ts(d1,c(2015,01),c(2016,03),频率= 12)ts2<-ts(d2,c(2015,01),c(2016,03),频率= 12)ts3<-ts(d3,c(2015,01),c(2016,03),频率= 12)#为ggplot准备数据dat<-ts.union(ts1,ts2,ts3)dat< -melt(dat,id.vars ="x")#添加日期日期<-seq(as.Date("2015-01-01"),as.Date("2016-03-01"),by ="months")dat $ Date<-日期p<-ggplot(dat,aes(x =日期,y =值,col = Var2))+geom_line(aes(linetype = Var2),size = 1)+geom_point(aes(shape = Var2),size = 2)+scale_linetype_manual(values = c(1,1,1))+scale_shape_manual(值= c(0,1,2))打印(p) 

解决方案

要使@Rui Barradas的解决方案更进一步,可以使用(v0.3.0)于2019年12月22日创建sup>

I would like to use ggplot2 to plot 3 time series in the same graph. I'd like to plot the first 2 series as solid lines without points. And I would like to plot the third series with points only and no line. How can I do that?

library(ggplot2)
library(reshape2)

d1 <- c(1, 2, 3, 2, 1, 2, 3, 4, 5, 6, 5, 4, 3, 1)
d2 <- c(0, 2, 4, 5, 4, 3, 2, 4, 6, 7, 6, 5, 3, 1)
d3 <- c(0, 1, 2, 4, 4, 2, 1, 3, 4, 7, 8, 3, 5, 0)

ts1 <- ts(d1, c(2015, 01), c(2016, 03), frequency = 12)
ts2 <- ts(d2, c(2015, 01), c(2016, 03), frequency = 12)
ts3 <- ts(d3, c(2015, 01), c(2016, 03), frequency = 12)

# prepare data for ggplot
dat <- ts.union(ts1, ts2, ts3)
dat <- melt(dat, id.vars = "x")

# add dates
dates <- seq(as.Date("2015-01-01"), as.Date("2016-03-01"), by = "months")
dat$Date <- dates

p <- ggplot(dat, aes(x = Date, y = value, col = Var2)) +
  geom_line(aes(linetype = Var2), size = 1) +
  geom_point(aes(shape = Var2), size = 2) +
  scale_linetype_manual(values = c(1, 1, 1)) +
  scale_shape_manual(values = c(0, 1, 2))
print(p)

解决方案

To take @Rui Barradas's solution one step further, you can use guide_legend/override.aes() to modify the legends for the lines and points by giving the lines NA shape and the points NA linetypes.

my_color <- setNames(c("red", "blue", "green"),
                     c('ts1', 'ts2', 'ts3'))
ggplot(dat, aes(x = Date, y = value, colour = Var2)) +
  geom_line(data = subset(dat, Var2 != "ts3")) +
  geom_point(data = subset(dat, Var2 == "ts3")) +
  scale_color_manual("Legend", values = my_color) +
  guides(color = guide_legend(override.aes = list(linetype = c(1,   1, NA),
                                                  shape    = c(NA, NA, 19)))) +
  theme_classic(base_size = 14)

Created on 2019-12-22 by the reprex package (v0.3.0)

这篇关于根据值绘制仅在线和仅点的一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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