In the following plot, I have two variables plotted side-by-side in a bar plot:
# 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)
Is it possible to have the two bars of a group partially overlap? i.e. the pink extends to the right partially over the blue, and vice-versa.
CodePudding user response:
What you could do is add position_dodge
to your geom_bar
like this:
# 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)
Created on 2022-07-19 by the reprex package (v2.0.1)