简体   繁体   English

如何在R中重叠具有相同y轴但不同x轴的2个图

[英]How to superimpose 2 plots with same y-axis, but different x-axes in R

Is there a way to superimpose two plots with different x-axes? 有没有办法用不同的x轴叠加两个图?

I have a dataset with systolic blood pressure of a patient at different days when they were taking different medications. 我有一个数据集,其中包含患者在服用不同药物时不同天的收缩压。 I would like to create a scatterplot of their SBP by date, and superimpose a boxplot of their SBPs at each medication. 我想按日期创建其SBP的散点图,并在每种药物上叠加其SBP的箱线图。 I created the two plots separately but can't figure out how to combine them in one figure. 我分别创建了两个图,但无法弄清楚如何将它们组合成一个图。

library(ggplot2)
library(lubridate)

df <- data.frame(date = c(ymd("2014-09-01") + c(1:5), ymd("2014-09-11") + c(1:5), ymd("2014-09-21") + c(1:5)), sbp1 = round(runif(n=15, min=130, max=200)), group = c(rep("A",5), rep("B",5), rep("C", 5))) 
p1 <- ggplot(df, aes(x=date, y=sbp1)) + geom_point(aes(color = group)) 
p2 <- ggplot(df, aes(x=group, y=sbp1)) + geom_boxplot(aes(x=group, y = sbp1)) 
p1
p2

P1 P2

You have to decide how to map the x coordinate into a single scale - eg like picking one date for the whole group: 您必须决定如何将x坐标映射到单个比例中-例如,像为整个组选择一个日期一样:

df %>%
  group_by(group) %>%
  mutate(groupdate = first(date) + 3) %>%
  ggplot(aes(y = sbp1)) +
  geom_boxplot(aes(x = groupdate, group = group)) +
  geom_point(aes(x = date, colour = group))

Then you can superimpose ggplot geometries on top of each other by + . 然后,您可以将ggplot几何图形彼此叠加+ Feels a bit hacky, but generates this: 感觉有点骇人听闻,但是会生成以下内容:

点和箱线图在同一轴上

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将自动绘图中呈现的两个图中的线系列组合成一个 plot,共享相同的 y 轴和两个不同的 x 轴? - How to combine the line series in two plots rendered in autoplot into a single plot, sharing the same y-axis and with two different x-axes? 在最小值处开始y轴,在0处开始x轴,并使用R中的matplot()使它们相交 - starting the y-axis at a minimum value, the x-axes at 0, and making them intersect using matplot() in R "在R中垂直堆叠多个图,具有相同的x轴但不同的Y轴" - Stacking multiple plots, vertically with the same x axis but different Y axes in R R ggplot facet - 共享y轴,多个不同的x轴 - R ggplot facet — shared y axis, multiple distinct x-axes r-在ggplot中用一个x轴绘制两个图(3个变量) - r - Ploting two plots (3 variables) with one x-axes in ggplot R, ggplot - 图形共享相同的 y 轴但具有不同的 x 轴比例 - R, ggplot - Graphs sharing the same y-axis but with different x-axis scales 相同的y轴,但不同的x轴图- - same y-axis but different x-axis graph - 如何在同一面板的同一X轴上绘制具有两个不同y轴范围的点? - How do I plot points with two different y-axis ranges on the same panel in the same X axis? 在R图中,如何使x轴的长度比y轴长几倍? - In R plots, how can we make the length of an x-axis several times longer than the y-axis? ggarrange 为具有相同 y 轴但注释不同高度的图形对齐 y 轴 - ggarrange align y-axes for graphs with same y-axis but annotations of different heights
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM