简体   繁体   中英

Alternative to geom_linerange and facets

I'd like to achieve a graph something like this using ggplot:

在此处输入图片说明

The closest I can get is:

ggplot(dat, aes(x = Date, color = Rain)) + 
geom_linerange(aes(ymin = 0, ymax = 1)) +
facet_wrap(~Station, ncol = 1)

which gives:

在此处输入图片说明

I can sort out all the formatting details. My question is: can I achieve this with Station on the y-axis instead of as a facet variable, as in the original?

I don't think geom_linerange is the right way to go for this. I tried putting Station as the y aesthetic but that didn't work. Is there another geom I could use instead?

As I commented above, I think geom_raster would be your best option here. Let's make up some data to see how it works.

library(ggplot)
dat <- data.frame(Date    = c(1:5, 1:5), 
                  Station = c(rep("A", 5), rep("B", 5)), 
                  Rain    = c(0,0,1,1,0, NA,1,0,1,1))

A simple plot would be,

ggplot(dat, aes(Date, Station)) + 
  geom_raster(aes(fill = factor(Rain)))

情节1

Now, the advantage of using geom_raster over geom_tile is that you can control the justification of the tile using hjust and vjust . Values for this go from 0 to 1, the default is 0.5, let's try replacing those for zeroes

ggplot(dat, aes(Date, Station)) + 
  geom_raster(aes(fill = factor(Rain)),
              hjust = 0,
              vjust = 0)

在此处输入图片说明

I think the default option works fine, I hope this helps. Cheers!

How about

ggplot(dat, aes(x = Date, color = Rain)) + 
    geom_linerange(aes(ymin = 0, ymax = 1)) +
    facet_wrap(Station ~ .)

Use facet_wrap instead of facet_grid puts the labels on the axis instead of cluttering up the whole grid by putting the labels on top of individual charts.

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