2017-11-02 6 views
1

매주 수집되는 데이터가 있습니다. 나는 매주 한 권씩 일련의 바이올린 음모를 보여주는 그래프를 원합니다. 그 위에, 나는 추세선을 갖고 싶다. 문제는 바이올린 플롯을 분리하기 위해 Week 변수가 하나의 요소 여야하지만 트렌드 라인을 플롯하기 위해서는 Week 변수가 연속적이어야한다는 것입니다. 둘 다 어떻게 얻습니까?일련의 바이올린 플롯에 트렌드 라인 플롯

Week = as.Date(c("2017-10-1", "2017-10-8", "2017-10-15")) 
mydata = data.frame(Week = sample(Week, 200, T), v_1 = sample.int(5, 200, T)) 

p1 = ggplot(mydata, aes(x = factor(Week), y = v_1)) # create the plot stub 
p1 + geom_violin()         # just violin plots 
p1 + geom_smooth(method = "lm")      # nothing 
p1 + geom_violin() + geom_smooth()     # just violin plots 

p2 = ggplot(mydata, aes(x = Week, y = v_1))  # new plot stuf 
p2 + geom_violin()        # single violin plot, not separated by week 
p2 + geom_smooth(method = "lm")     # trend line 
p2 + geom_violin() + geom_smooth(method = "lm") # trend line over single violin plot 

답변

1
# Generate data from 3 normal distributions with means -3, 3, and 6 
set.seed(1) 
n <- 200 
dates <- as.Date(c("2017-10-1", "2017-10-8", "2017-10-15")) 
mydata = data.frame(Week = rep(dates,each=n), v_1 = c(rnorm(n,-3),rnorm(n,3),rnorm(n,6))) 

# Estimate a linear regression model: x is the group number 
cf <- coef(lm(v_1~as.numeric(factor(Week)), data=mydata)) 

# Plot means (red dots) and the regression line (trend) 
library(ggplot2) 
ggplot(mydata, aes(x = factor(Week), y = v_1)) + 
geom_violin() + 
stat_summary(aes(group=1),fun.y=mean, geom="point", color="red", size=3) + 
geom_abline(slope=cf[2], intercept=cf[1], lwd=.8) 

enter image description here