且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为 R 中跨 x 轴镜像的两个变量创建条形图?

更新时间:2023-11-09 22:42:40

使用 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")