如何为R中的x轴镜像的两个变量创建条形图? [英] How do you create a bar plot for two variables mirrored across the x-axis in R?
问题描述
我有一个包含x变量和两个y1和y2变量(总共3列)的数据集。我想将y1对x绘制为轴上方的条形图,将y2绘制在x轴下面的同一个绘图中的同一个x上,这样两个条形图互为镜像。
下面的图D是我尝试去做的一个例子。
ggplot 使用alt =图** D **> code>你可以这样做:
设置数据。这里没有什么奇怪的,但显然轴下面的值是负值。
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))
)
使用 ggplot
和 geom_bar
。要防止 geom_bar
汇总数据,请指定 stat =identity
。同样,通过指定 position =identity
。
library(ggplot2)
ggplot(dat,aes(x = x,y = y,fill = group))+
geom_bar(stat =identity,position =identity)
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.
Figure D below is an example of what I am trying to do.
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))
)
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屋!