繁体   English   中英

如何在ggplot2中按组定义条形重叠程度?

[英]How to define a degree of bar overlap by group in ggplot2?

在下图中,我在条形图中并排绘制了两个变量:

# required libraries
library(ggplot2)
library(reshape2)

# Make data
data(cars)
cars_scaled <- as.data.frame(scale(cars[1:10,]))
cars_scaled$id <- seq(nrow(cars_scaled))
cars_scaled <- melt(cars_scaled, id.vars = "id")
cars_scaled

# plot
ggplot(cars_scaled) + aes(x = id, y = value, group = variable, fill = variable) +
  geom_bar(stat="identity", position = "dodge", width = 0.8, col = 1, alpha = 0.5)

在此处输入图像描述

是否可以让一组中的两个条部分重叠? 即粉红色在蓝色部分上方向右延伸,反之亦然。

您可以做的是将position_dodge添加到您的geom_bar ,如下所示:

# required libraries
library(ggplot2)
library(reshape2)

# Make data
data(cars)
cars_scaled <- as.data.frame(scale(cars[1:10,]))
cars_scaled$id <- seq(nrow(cars_scaled))
cars_scaled <- melt(cars_scaled, id.vars = "id")
cars_scaled
#>    id variable       value
#> 1   1    speed -1.60356745
#> 2   2    speed -1.60356745
#> 3   3    speed -0.40089186
#> 4   4    speed -0.40089186
#> 5   5    speed  0.00000000
#> 6   6    speed  0.40089186
#> 7   7    speed  0.80178373
#> 8   8    speed  0.80178373
#> 9   9    speed  0.80178373
#> 10 10    speed  1.20267559
#> 11  1     dist -1.40818923
#> 12  2     dist -0.59772061
#> 13  3     dist -1.20557208
#> 14  4     dist  0.61798233
#> 15  5     dist  0.01013086
#> 16  6     dist -0.59772061
#> 17  7     dist  0.21274801
#> 18  8     dist  1.02321664
#> 19  9     dist  1.83368526
#> 20 10     dist  0.11143944

# plot
ggplot(cars_scaled, aes(x=id, y=value, fill=variable, group = variable)) + 
  geom_bar(position=position_dodge(.7), stat="identity", width = 0.8, col = 1, alpha = 0.5)

reprex 包于 2022-07-19 创建 (v2.0.1)

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM