如何用不连续数据绘制折线图?

时间:2014-03-05 19:24:46

标签: r ggplot2

我在使用R中的ggplot2库绘制图表时遇到问题 我有一个'日期'变量,其中包含每个3'品牌'品牌的披露值'评级'的日期。事情是,在一次活动之后,市场只有两个品牌共享。因此,我想分别在此事件之前和之后绘制线条,尽管在同一个图中。可能吗?如果我用平滑函数绘制所有图形,图表就没有意义,所以我必须在两个阶段之间留下一个,在下面的日期中介于“16/09/2012”和“18/09/2012”之间或者在第五和第六元素之间。

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) )

2 个答案:

答案 0 :(得分:4)

作为替代方案,并使用@ jlhoward的Event变量: 使用BrandEvent之间的互动作为分组变量,然后在一个面板中绘制,将不连续性显示为阴影区域。

data$Event <- "Before"
data[data$Date>="2012-09-18",]$Event <- "After"
data$Event <- factor(data$Event, levels=c("Before","After"))

xmin <- as.Date("16/09/2012", "%d/%m/%Y") # Beginning and end of discontinuity
xmax <- as.Date("18/09/2012", "%d/%m/%Y")
ggplot(data) +
  geom_line(aes(x = Date, y = Rating, colour = Brand, group=interaction(Brand, Event)), size = 1) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "salmon", alpha = .01)

enter image description here

修改 现在添加geom_smooth

ggplot(data) +
  geom_line(aes(x = Date, y = Rating, colour = Brand, group = interaction(Brand, Event)), size = .5) +
  geom_smooth(aes(x=Date, y=Rating, colour = Brand, group = interaction(Brand, Event)), method="loess", size=1, se=F) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), fill = "salmon", alpha = .01)

enter image description here

答案 1 :(得分:2)

这样的东西?

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,它在事件之前采用“之前”值,在事件之后采用“之后”。然后我们在ggplot中使用facet来分隔Before和After。

原因:

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

是创建一个有序因子:ggplot想要按字母顺序(After,然后是Before)绘制facet,除非我们这样做。