I want to layer something specifically on one of the dodged bars, how would I be able to do that?
In the below example, I want to layer something specifically on A3 in the cat3 group on the barplot. I know that x = 3 for cat3 but because of the interdependence of the widths for dodge and bar width it seems difficult to target that one bar. Is there any formula that i can use to calculate the x coordinate? I have provided an example code below. thanks
x1 <- c(15,75,28,60,80,100)
x2 <- c('cat1','cat2','cat3','cat1','cat2','cat3')
x3 <- c('A1','A2','A3','A4','A1','A2')
data=data.frame(cbind(x1,x2,x3),stringsAsFactors = F)
data$x1 <- as.numeric(data$x1)
data$x2 <- factor(data$x2)
data$x3 <- factor(data$x3)
ggplot(data,aes(y = x1, x = x2)) + geom_bar(stat = 'identity',
aes(fill = data$x3, width = 0.5),
position = position_dodge(width = 0.8))
The
width
argument inposition_dodge()
is specifying the distance between the leftmost edge of the left bar and the rightmost edge of the right bar. With a dodge width of 0.8, the distance between your start point of x = 3 for your x3 category and the edge of either bar is 0.4 (+0.4 on the right and -0.4 on the left) Half of 0.4 (i.e. 0.2) will bring you to midpoint of the bar (again +0.2 on the right and -0.2 on the left). This is true irrespective of the bar width.Here's an example where I've drawn an H on the right bar in cat3. The y-units line up with those on the y-axis.