簡體   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