![](/img/trans.png)
[英]How to combine different layers in r ggplot with 2 different datasets - one for map & other for geom_area?
[英]How to combine layers based on different datasets with ggplot2 in R
我想制作一個顯示時間序列的圖,然后顯示一組預測分布,每個分布都以小提琴圖表示。 下面的示例代碼分別創建和繪制一個時間序列(作為線圖)和兩個小提琴圖。
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()
如何將它們組合成一個圖表,並具有從時間點1到50(沿x軸)的線圖,然后分別是在時間點51和52的兩個小提琴圖?
我不確定您是否可以在同一軸上繪制離散變量和連續變量。 因此,您必須妥協。 Markus選擇離散化x
變量,而我更喜歡使y
變量連續。 注意,我已經更改了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)))
您需要將y$time
因子級別轉換為integer
,添加分組變量,然后將data = ...
移動到特定幾何。
# 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.