gpt4 book ai didi

r - 如何绘制不连续数据的折线图?

转载 作者:行者123 更新时间:2023-12-01 15:16:07 24 4
gpt4 key购买 nike

我在使用 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) )

最佳答案

通过另一种方式,使用@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

关于r - 如何绘制不连续数据的折线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22207246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com