简体   繁体   English

将 ggplot geom_polygon 扩展到绘图结束

[英]Extending ggplot geom_polygon to end of plot

How can I make a confidence interval band that extends to the end of the plot in ggplot?如何在ggplot中制作一个延伸到绘图末尾的置信区间带?

I can do it if the plotted band is entirely within the plot, for example例如,如果绘图带完全在绘图内,我可以这样做

limits <- c(1e2, 1e7)
confPolygon <- tibble(
    x = c(limits[1], limits[1]*10, limits[2], limits[2], limits[2]/10, limits[1], limits[1]), 
    y = c(limits[1], limits[1], limits[2]/10, limits[2], limits[2], limits[1]*10, limits[1])
)
plot <- ggplot() + 
    geom_polygon(data = confPolygon, aes(x = x, y = y), fill = "grey", alpha = .25) +
    scale_x_log10(limits = limits) + 
    scale_y_log10(limits = limits)

works.作品。 However, if I try any shape that extends the polygon to the edges但是,如果我尝试将多边形扩展到边缘的任何形状

confPolygon <- tibble(
    x = c(limits[1], limits[2]*10, limits[2]*10, limits[1], limits[1]), 
    y = c(limits[1], limits[1], limits[2]*10, limits[2]*10, limits[1])
)

then it doesn't plot the polygon.然后它不会绘制多边形。

The reason is because the method you are using to zoom in to the plot (setting limits within the x or y scales) isn't meant to zoom in;原因是您用来放大绘图的方法(在 x 或 y 范围内设置限制)并不是要放大; it actually subsets the data, accidentally creating missing values on the way.它实际上对数据进行了子集化,在途中意外地创建了缺失值。 Use coord_cartesian(xlim = c(0,5), ylim = c(0,5)) , or in your case, coord_cartesian(xlim = limits, ylim = limits) instead, as this step does not subset the data.使用coord_cartesian(xlim = c(0,5), ylim = c(0,5)) ,或者在您的情况下,使用coord_cartesian(xlim = limits, ylim = limits) ,因为此步骤不会对数据进行子集化。

One way to do this is with oob=scales::squish() .一种方法是使用oob=scales::squish()

plot2 <- ggplot() + 
  geom_polygon(data = confPolygon, aes(x = x, y = y), fill = "grey", alpha = .25) +
  scale_x_log10(limits = limits, oob=scales::squish) + 
  scale_y_log10(limits = limits, oob=scales::squish)

If you really want the polygon to extend all the way to the edge, you should also add expand=c(0,0) to each of the scale_*_log10() argument lists.如果您真的希望多边形一直延伸到边缘,您还应该将expand=c(0,0)到每个scale_*_log10()参数列表中。

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

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