简体   繁体   English

替代geom_linerange和facets

[英]Alternative to geom_linerange and facets

I'd like to achieve a graph something like this using ggplot: 我想使用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? 我的问题是:我可以使用y轴上的Station来实现此目的,而不是像原始版本中那样将其作为facet变量吗?

I don't think geom_linerange is the right way to go for this. 我认为geom_linerange不是geom_linerange目的的正确方法。 I tried putting Station as the y aesthetic but that didn't work. 我尝试将Station当作y美学对象,但这没有用。 Is there another geom I could use instead? 还有其他我可以使用的几何图形吗?

As I commented above, I think geom_raster would be your best option here. 如上所述,我认为geom_raster将是您的最佳选择。 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 . 现在,使用geom_raster不是geom_tile的优势在于,您可以使用hjustvjust来控制图块的vjust Values for this go from 0 to 1, the default is 0.5, let's try replacing those for zeroes 值从0到1,默认值为0.5,让我们尝试将其替换为零

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. 使用facet_wrap代替facet_grid将标签放在轴上,而不是通过将标签放在单个图表的顶部来使整个网格facet_grid

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

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