How to drop unused factors in faceted R ggplot box

2019-05-14 02:54发布

Below is some example code I use to make some boxplots:

stest <- read.table(text="    site  year    conc
    south   2001    5.3
    south   2001    4.67
    south   2001    4.98
    south   2002    5.76
    south   2002    5.93
    north   2001    4.64
    north   2001    6.32
    north   2003    11.5
    north   2003    6.3
    north   2004    9.6
    north   2004    56.11
    north   2004    63.55
    north   2004    61.35
    north   2005    67.11
    north   2006    39.17
    north   2006    43.51
    north   2006    76.21
    north   2006    158.89
    north   2006    122.27
", header=TRUE)

require(ggplot2)
ggplot(stest, aes(x=year, y=conc)) +
  geom_boxplot(horizontal=TRUE) +
  facet_wrap(~site, ncol=1) +
  coord_flip() +
  scale_y_log10()

Which results in this:

boxplot

I tried everything I could think of but cannot make a plot where the south facet only contains years where data is displayed (2001 and 2002). Is what I am trying to do possible?

Here is a link (DEAD) to the screenshot showing what I want to achieve:

标签: r ggplot2
2条回答
虎瘦雄心在
2楼-- · 2019-05-14 03:43

A simple way to circumvent your problem (with a fairly good result):
generate separately the two boxplots and then join them together using the grid.arrange command of the gridExtra package.

library(gridExtra)

p1 <- ggplot(subset(stest,site=="north"), aes(x=factor(year), y=conc)) +
 geom_boxplot(horizontal=TRUE) + coord_flip() + scale_y_log10(name="")

p2 <- ggplot(subset(stest,site=="south"), aes(x=factor(year), y=conc)) +
 geom_boxplot(horizontal=TRUE) + coord_flip() + 
 scale_y_log10(name="X Title",breaks=seq(4,6,by=.5)) +

grid.arrange(p1, p2, ncol=1)
查看更多
Anthone
3楼-- · 2019-05-14 03:57

Use the scales='free.x' argument to facet_wrap. But I suspect you'll need to do more than that to get the plot you're looking for.

Specifically aes(x=factor(year), y=conc) in your initial ggplot call.

查看更多
登录 后发表回答