简体   繁体   中英

R combining a box plot with a bar plot works but not the other way around

I am trying to combine two plots in R. I want a bar chart on top of which I plot in the second step a box plot to overlay the two information.

This works if I plot the box plot first and then the bar plot but this looks ugly for the bar covering half of the box behind it. Turning these two around is the obvious solution but this fails with Discrete value supplied to continuous scale . I am aware of the alpha parameter to add transparency but I really would like to understand why this error occurs if the order of the plots is swapped.

Here is a MWE:

library(ggplot2) 
a_box <- matrix(c(1.3, 2.4, 5.2, 2.3, 4.2,2.1), ncol=2, nrow=3)
a_box <- data.frame(a_box)
a_box <- stack(a_box)
# bar plot should plot the mean values
# I add 'index' values for each mean to the vector
a <- matrix(c(2.9, 2.8, 1.0, 2.0), nrow=2, ncol=2)
a <- data.frame(a)
colnames(a) <- c('values', 'index')
# Combining both plots - first box then bar works
ggplot() + geom_boxplot(data=a_box, aes(ind, values)) + geom_bar(data=a, aes(a$index, a$values), stat='identity')
# the other way around not - 'Discrete value supplied to continuous scale' - why?
ggplot() +  geom_bar(data=a, aes(a$index, a$values), stat='identity', alpha=0.3) + geom_boxplot(data=a_box, aes(ind, values))

What do I have to do to make this work in the desired order?

You're trying to plot two datasets with different x-axis. One discrete ( a_box ) and one "continous" ( a ). To overcome this you can map the x-axis from ( a_box ) to the geom_barplot call and it will work fine.

ggplot() +  geom_bar(data=a, aes(unique(a_box$ind), a$values), stat='identity', alpha=0.3) + geom_boxplot(data=a_box, aes(ind, values))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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