如何绘制带有不连续数据的折线图? [英] How to plot a line graph with discontinuity data?

查看:116
本文介绍了如何绘制带有不连续数据的折线图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用R中的ggplot2库绘制图形时遇到问题.我有一个'Date'变量,其中包含3个'Brand'品牌中每个品牌的披露值'Rating'的日期.问题是,事件发生后,市场仅由两个品牌共享.因此,我想在此事件之前和之后分别绘制线条,尽管在同一图中.是否可以?如果我使用平滑函数按原样绘制所有图表,那么图表将毫无意义,因此我必须在两个阶段之间保持迄今为止的状态,这两个阶段的日期在"16/09/2012"和"18/09/2012"之间或介于第五和第六个元素之间.

I've a problem plotting a graph using ggplot2 library in R. I have a 'Date' variable containing date of disclosed values 'Rating' for each of the 3 'Brand' brands. The thing is that after an event, the market is only shared by two brands. So, I want to plot lines for before and after this event separately although in the same plot. Is it possible? If I plot everything as is with a smoothing function, the chart gets no sense, so I must leave an hitherto between the two phases, which in the date below is between "16/09/2012" and "18/09/2012" or between the fifth and sixth elements.

x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
as.Date(x, "%d%b%Y")
x <- c("10/09/2012", "12/09/2012", "11/09/2012")
as.Date(x, "%d/%m/%Y")

x <- c("12/09/2012", "13/09/2012", "14/09/2012", "15/09/2012","16/09/2012","18/09/2012","19/09/2012","20/09/2012","22/09/2012","23/09/2012")
x <- as.Date(x, "%d/%m/%Y")
y <-c(30,32,33,34,35,45,46,44,46,47)
y2<-c(20,22,23,27,29,55,54,56,54,53)
y3 <- c(10,10,10,7,6,NA,NA,NA,NA,NA)
data1 <- data.frame(x,y1)
data1$w <-"A"
data2 <- data.frame(x,y2)
data2$w <-"B"
data3 <- data.frame(x,y3)
data3$w <-"C"

colnames(data1)<- c("Date", "Rating", "Brand")
colnames(data2)<- c("Date", "Rating", "Brand")
colnames(data3)<- c("Date", "Rating", "Brand")

data <-rbind(data1,data2,data3)

#Chart
(plot <-ggplot(data, aes(x=Date, 
y=Rating, colour=Brand, group=Brand)) 
+ geom_line(size=.5)
+ geom_smooth(aes(x=Date, y=Rating), 
method="loess", size=3, se=F) )

推荐答案

像这样吗?

data$Event <- "Before"
data[data$Date>="2012-09-18",]$Event <- "After"
data$Event <- factor(data$Event, levels=c("Before","After"))
#Chart
ggplot(data,aes(x=Date, y=Rating, colour=Brand, group=Brand))+
 geom_line(size=.5) +
 geom_smooth(aes(x=Date, y=Rating), method="loess", size=1, se=F)+ 
   facet_wrap(~Event, scales="free_x")

这将添加新列 data $ Event ,该列在事件之前具有值"Before",在事件之后具有"After".然后,我们使用ggplot中的构面将之前"和之后"分开.

This adds a new column, data$Event which takes on values "Before" before the event and "After" after the event. Then we use facets in ggplot to separate Before and After.

原因:

data$Event <- factor(data$Event, levels=c("Before","After"))

是要创建有序因子:ggplot希望按字母顺序(从之后"到之前")绘制构面,除非我们这样做.

is to create an ordered factor: ggplot wants to plot the facets in alphabetical order (After, then Before), unless we do this.

这篇关于如何绘制带有不连续数据的折线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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