如何使用R中的ggplot2组合基于不同数据集的图层
我想生成一个图,显示一个时间序列,然后是一组预测分布,每个分布都表示为小提琴图。下面的示例代码分别创建并绘制一个时间序列(作为线图)和两个小提琴图如何使用R中的ggplot2组合基于不同数据集的图层,r,ggplot2,R,Ggplot2,我想生成一个图,显示一个时间序列,然后是一组预测分布,每个分布都表示为小提琴图。下面的示例代码分别创建并绘制一个时间序列(作为线图)和两个小提琴图 set.seed(12345) x <- data.frame(time=1:50, dat=rnorm(50)) y1 <- rnorm(500) y2 <- rnorm(500, sd=5) y <- data.frame(time=as.factor(c(rep(51,500),rep(52,500))), dat=c
set.seed(12345)
x <- data.frame(time=1:50, dat=rnorm(50))
y1 <- rnorm(500)
y2 <- rnorm(500, sd=5)
y <- data.frame(time=as.factor(c(rep(51,500),rep(52,500))), dat=c(y1,y2))
ggplot(x, aes(x=time, y=dat)) +
geom_line()
ggplot(y, aes(x=time, y=dat)) +
geom_violin()
set.seed(12345)
我不确定你能在同一个轴上画出离散变量和连续变量。所以你必须妥协。Markus选择了离散化x
变量,而我更喜欢将y
变量转换为连续变量。请注意,我已经更改了生成y
的方式(删除了该因子)
库(ggplot2)
种子集(12345)
x
您需要将y$time
因子级别转换为integer
,添加分组变量,并将数据=…
移动到特定几何体。
#将因子变量转换为其因子级别
你需要多少时间:ggplot(mapping=aes(x=as.factor(time),y=dat))+geom_线(data=x,aes(group=1))+geom_小提琴(data=y)
?哈,该死的,你赢了我。等待时间太长,无法发布。:-)
library(ggplot2)
set.seed(12345)
x <- data.frame(time=1:50, dat=rnorm(50))
y1 <- rnorm(500)
y2 <- rnorm(500, sd=5)
y <- data.frame(time=c(rep(51, 500), rep(52, 500)), dat=c(y1,y2))
ggplot(x, aes(x = time, y = dat)) +
theme_bw() +
scale_x_continuous(limits = c(0, 52)) +
geom_line() +
geom_violin(data = y, aes(group = as.factor(time)))
# Transform your factor variable to its factor levels
y$time <- as.integer(levels(y$time))[y$time]
# Plot with grouping for the violin plot (as x is not a factor anymore)
ggplot() +
geom_line(data = x, aes(x = time, y = dat)) +
geom_violin(data = y, aes(x = time, y = dat, group = time))