简体   繁体   中英

ggplot2: strange behaviour of geom_boxplot

I want to produce a grouped boxplot, so first I modified a piece of code I found on the internet ( http://www.r-bloggers.com/ggplot2-multiple-boxplots-with-metadata/ ) to generate a dataframe of test values:

    Y <- data.frame(
      values = c(rnorm(mean=20, sd=4, n=3), rnorm(mean=10, sd=2, n=3), rnorm(mean=50, sd=10, n=3), rnorm(mean=60, sd=12, n=3)),
      factor1 = rep(c('oil1', 'oil2'), each = 3),
      factor2 = rep(c('product1', 'product2'), each = 6)
   )

    values  factor1 factor2
1   13.527314   oil1    product1
2   23.495898   oil1    product1
3   14.881210   oil1    product1
4   9.110103    oil2    product1
5   9.330372    oil2    product1
6   10.846560   oil2    product1
7   40.786020   oil1    product2
8   43.157393   oil1    product2
9   43.050182   oil1    product2
10  39.588651   oil2    product2
11  65.963630   oil2    product2
12  63.425253   oil2    product2

Then, the code:

ggplot(Y, aes(x = factor2, y = values, fill = factor1)) +
  geom_boxplot()

produces the boxplot I want.

My real data are in this other data frame, created reading a .csv file:

    values  factor1 factor2
1   0.2 oil1    product1
2   1.7 oil1    product1
3   3.2 oil1    product1
4   27.8    oil2    product1
5   29.8    oil2    product1
6   31.8    oil2    product1
7   0   oil1    product2
8   1   oil1    product2
9   2.5 oil1    product2
10  29.3    oil2    product2
11  31.3    oil2    product2
12  33.3    oil2    product2

(I am unable to correct the misalignement in this table) Yet when I try to create a boxplot using the code above, instead of the boxes the plot contains horizontal segments at y=value.

How can I resolve this problem?

In fact, I realized that geom_crossbar is better for what I want to do.

Which is, values on the Y-axis; factor2 on the X-axis; different fill colors for oil1 and oil2; one colored bar extending from minimum to maximum of value and centered around the mean for each oil+product combination (for a total of 4 bars)

The result should look like the image in this answer to a similar question: https://stackoverflow.com/a/21561408/4518857

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