英文:
Plotting values from different dataframes side by side within same group
问题
我有两个数据框(Foo和Bar),它们的结构如下:
Group AME lower upper
A . . .
B . . .
C . . .
Foo和Bar都有相同数量的分组,分组名称相同,但是"AME"、"lower"和"upper"下的值在每个数据框中是不同的。目前,我将Foo和Bar的数据分别显示在不同的图表上,每个图表的Y轴是分组,X轴是在"AME"下列出的该分组的值,"lower"和"upper"确定了该值的误差棒的边界。以下是我的代码:
ggplot(aes(x=Group, y=AME)) +
geom_point() +
geom_errorbar(aes(ymin=lower,ymax=upper),width=0)+
geom_hline(yintercept = 0, color="gray", linetype="longdash")+
coord_flip()
然而,我想要做的是在同一图表上显示两个数据框的数据,如下所示:
我应该如何实现这个目标?
1: https://i.stack.imgur.com/n2N2K.jpg
英文:
I have two dataframes (Foo and Bar) that each look like this:
Group AME lower upper
A . . .
B . . .
C . . .
Both Foo and Bar have the same number of groups and the groups have the same names, but the values under "AME," "lower" and "upper" are different in each. Currently, I'm displaying the data in Foo and Bar on separate plots such that the Y axis of each plot is the group, the X axis is the value listed for that group under "AME", and "lower" and "upper" determine the bounds of an error bar for that value. Here is my code:
ggplot(aes(x=Group, y=AME)) +
geom_point() +
geom_errorbar(aes(ymin=lower,ymax=upper),width=0)+
geom_hline(yintercept = 0, color="gray", linetype="longdash")+
coord_flip()
However, what I'd like to do is display the data in both dataframes on the same plot like shown below:
How can I do this?
答案1
得分: 3
如评论中已经概述的那样,通过行绑定您的数据并使用 `position_dodge`。
使用一些虚假的示例数据:
``` r
library(ggplot2)
library(dplyr, warn = FALSE)
foo <- data.frame(
Group = LETTERS[1:3],
AME = 1:3,
lower = 0:2,
upper = 2:4
)
bar <- data.frame(
Group = LETTERS[1:3],
AME = rev(1:3),
lower = rev(0:2),
upper = rev(2:4)
)
pd <- position_dodge(width = .6)
dplyr::lst(foo, bar) %>%
dplyr::bind_rows(.id = "Key") %>%
ggplot(aes(y = Group, x = AME, shape = Key)) +
geom_point(position = pd) +
geom_errorbar(aes(xmin = lower, xmax = upper), width = 0, position = pd) +
geom_vline(xintercept = 2, color = "gray", linetype = "longdash")
<details>
<summary>英文:</summary>
As already outlined in the comments bind your data by rows and use `position_dodge`.
Using some fake example data:
``` r
library(ggplot2)
library(dplyr, warn = FALSE)
foo <- data.frame(
Group = LETTERS[1:3],
AME = 1:3,
lower = 0:2,
upper = 2:4
)
bar <- data.frame(
Group = LETTERS[1:3],
AME = rev(1:3),
lower = rev(0:2),
upper = rev(2:4)
)
pd <- position_dodge(width = .6)
dplyr::lst(foo, bar) |>
dplyr::bind_rows(.id = "Key") |>
ggplot(aes(y = Group, x = AME, shape = Key)) +
geom_point(position = pd) +
geom_errorbar(aes(xmin = lower, xmax = upper), width = 0, position = pd) +
geom_vline(xintercept = 2, color = "gray", linetype = "longdash")
<!-- -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论