gpt4 book ai didi

r - 使用 ggplot2 和网格对齐离散轴和连续轴

转载 作者:行者123 更新时间:2023-12-02 10:46:45 24 4
gpt4 key购买 nike

我正在尝试显示几个变量的每周汇总数据的网格图。该图最相关的两个组成部分是特定变量在给定一周内所占值的分布汇总图(即箱线图或 fiddle 图)和整数变量在数周内累积的累积计数图(因此步骤图)。我想使用网格在对齐的 x 轴上绘制这两个图。我将使用 ggplot2 来制作各个图表,因为我很喜欢 Hadley Wickham(j/k,ggplot 真的非常非常好)。

问题在于,geom_boxplot 仅采用 x 轴的因子,而 geom_step 仅采用 x 轴的连续数据。即使您使用 coord_cartesianscale_x_... 强制执行类似的 x 限制,这些也不一定对齐。

我已经使用geom_rect拼凑了一个技巧,该技巧将适用于这个特定的应用程序,但是如果例如我有一些其他因素导致出现多个框,那么适应起来就会很痛苦一周。

强制性的可重现:

library(ggplot2)
library(grid)

var1 <- data.frame(val = rnorm(300),
week = c(rep(25, 100),
rep(26, 100),
rep(27, 100))
)

var2 <- data.frame(cumul = cumsum(c(0, rpois(2, 15))),
week = c(25, 26, 27)
)


g1 <- ggplot(var1, aes(x = factor(week), y = val)) +
geom_boxplot()

g2 <- ggplot(var2, aes(x = week, y = cumul)) +
geom_step() + scale_x_continuous(breaks = 25:27)

grid.newpage()
grid.draw(rbind(ggplotGrob(g1),
ggplotGrob(g2),
size = "last"))

Example of non-aligned continuous and discrete axes

还有杂凑:

library(dplyr)

chiggity_check <- var1 %>%
group_by(week) %>%
summarise(week.avg = mean(val),
week.25 = quantile(val)[2],
week.75 = quantile(val)[4],
week.05 = quantile(val)[1],
week.95 = quantile(val)[5])

riggity_rect <- ggplot(chiggity_check) +
geom_rect(aes(xmin = week - 0.25, xmax = week + 0.25,
ymin = week.25,
ymax = week.75)) +
geom_segment(aes(x = week - 0.25, xend = week + 0.25,
y = week.avg, yend=week.avg),
color = "white") +
geom_segment(aes(x = week, xend = week ,
y = week.25, yend=week.05)) +
geom_segment(aes(x = week, xend = week ,
y = week.75, yend=week.95)) +
coord_cartesian(c(24.5,27.5)) +
scale_x_continuous(breaks = 25:27)

grid.newpage()
grid.draw(rbind(ggplotGrob(riggity_rect),
ggplotGrob(g2 + coord_cartesian(c(24.5,27.5))),
size = "last"))

Example of kludged together grid graph

所以问题是:有没有办法强制geom_boxplot到连续轴或geom_step到因子轴?或者是否有其他一些实现,也许 stat_summary 会更灵活一些,以便我可以对齐轴,并且还可以轻松添加诸如分组颜色变量之类的内容?

最佳答案

一种方法是在使用 factor(week) 设置的 x 轴上绘制两个图表,但在 g2 图(阶梯图)中,请在 geom_blank() 中执行此操作 以便设置比例。然后在geom_step()中,以数字刻度绘制:as.numeric(factor(week))

library(ggplot2)
library(grid)

# Your data
var1 <- data.frame(val = rnorm(300),
week = c(rep(25, 100),
rep(26, 100),
rep(27, 100))
)

var2 <- data.frame(cumul = cumsum(c(0, rpois(2, 15))),
week = c(25, 26, 27)
)

# Your g1
g1 <- ggplot(var1, aes(x = factor(week), y = val)) +
geom_boxplot()

# Modified g2
g2 <- ggplot(var2) + geom_blank(aes(x = factor(week), y = cumul)) +
geom_step(aes(x = as.numeric(as.factor(week)), y = cumul))

grid.newpage()
grid.draw(gridExtra::rbind.gtable(ggplotGrob(g1),
ggplotGrob(g2),
size = "last"))

enter image description here

关于r - 使用 ggplot2 和网格对齐离散轴和连续轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31299843/

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