简体   繁体   中英

R Plotting (ggplot2) - Bar and box plot on same figure

I'm trying to plot a double-y axis plot with R. It should have a bar plot for one set of data, and a box plot for the other. Here's what I have so far:

set.seed(1)
boxData <- data.frame(group=rep(1:4, 10),measurement=matrix(rnorm(40), nrow=40))
barData <- data.frame(group=1:4, measurement=matrix(runif(4), nrow=4)*5)

p1 <- ggplot(boxData, aes(factor(group), measurement))
p1 <- p1 + geom_boxplot(width=0.2, position=position_dodge(width=0.2))
p1

p2 <-p1 + geom_bar(data=barData, aes(factor(group), measurement),stat="identity",
               width=0.2, position=position_fill(width=0.2), colour="black")
p2

There are two things that I need to fix:

  1. The bars and boxes should be offset to the left and right, so they're not overlayed.
  2. There should be a axis on the right side for the boxplot.

Unless you get very good a grid , the dual y axis isn't going to happen. You can "fake" the dodging by doing something like this:

p1 <- ggplot(boxData, aes(x = group - 0.1, measurement,group = group))
p1 <- p1 + geom_boxplot(width=0.2, position=position_dodge(width=0.2))
p1

p2 <-p1 + geom_bar(data=barData, aes(x = group + 0.1, measurement,group = group),
                   stat="identity",width=0.2, colour="black")
p2

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