【问题标题】:plot trend line over a series of violin plots在一系列小提琴图上绘制趋势线
【发布时间】:2018-04-15 01:16:52
【问题描述】:

我有每周收集的数据。我想要一个显示一系列小提琴图的图表,每周一个。最重要的是,我想要一条趋势线。问题似乎是,为了分离小提琴图,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

【问题讨论】:

    标签: r ggplot2 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)
    

    【讨论】:

    • 好的,所以通过在回归模型中执行as.numeric(factor(Week)),您可以将日期值替换为其因子水平(1、2、3)。然后,由于图中的水平轴实际上是这些因子水平的比例(日期仅显示为标签),因此绘制的任何内容都使用因子水平,因为 x 值将正确显示与日期一起绘制,对?整洁。
    • @PauldeBarros 对!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 2021-08-28
    • 2023-03-06
    相关资源
    最近更新 更多