简体   繁体   English

R将箱形图与条形图结合使用有效,但反之则不行

[英]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. 我正在尝试在R中合并两个图。我想要一个条形图,在第二个步骤中,我要绘制一个箱形图以覆盖这两个信息。

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 . 解决这两个问题是显而易见的解决方案,但是由于将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. 我知道alpha参数可以增加透明度,但是我真的很想了解如果交换绘图顺序会为什么会发生此错误。

Here is a MWE: 这是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. 您正在尝试绘制x轴不同的两个数据集。 One discrete ( a_box ) and one "continous" ( a ). 一个离散( a_box )和一个“连续”( a )。 To overcome this you can map the x-axis from ( a_box ) to the geom_barplot call and it will work fine. 为了克服这个问题,您可以将x轴从( a_box )映射到geom_barplot调用,它将正常工作。

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))

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

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