如何为 R 中跨 x 轴镜像的两个变量创建条形图? [英] How do you create a bar plot for two variables mirrored across the x-axis in R?

查看:28
本文介绍了如何为 R 中跨 x 轴镜像的两个变量创建条形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,其中包含一个 x 变量和两个 y1 和 y2 变量(总共 3 列).我想将 y1 与 x 绘制为轴上方的条形图,将 y2 与 x 轴下方同一图中的相同 x 绘制成条形图,以便两个条形图相互镜像.

I have a dataset with an x variable and two y1 and y2 variables (3 columns in total). I would like to plot y1 against x as a bar plot above the axis and y2 against the same x in the same plot underneath the x axis so that the two bar plots mirror each other.

下面的图 D 是我正在尝试做的一个例子.

Figure D below is an example of what I am trying to do.

推荐答案

使用 ggplot 你可以按照如下方式进行:

Using ggplot you would go about it as follows:

设置数据.这里没有什么奇怪的,但显然轴下方的值将为负.

Set up the data. Nothing strange here, but clearly values below the axis will be negative.

dat <- data.frame(
    group = rep(c("Above", "Below"), each=10),
    x = rep(1:10, 2),
    y = c(runif(10, 0, 1), runif(10, -1, 0))
)

使用 ggplotgeom_bar 绘图.要防止 geom_bar 汇总数据,请指定 stat="identity".同样,需要通过指定position="identity"来禁用堆叠.

Plot using ggplot and geom_bar. To prevent geom_bar from summarising the data, specify stat="identity". Similarly, stacking needs to be disabled by specifying position="identity".

library(ggplot2)
ggplot(dat, aes(x=x, y=y, fill=group)) + 
  geom_bar(stat="identity", position="identity")

这篇关于如何为 R 中跨 x 轴镜像的两个变量创建条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆