如何使用刻面为ggplot2中的轴仅设置一个限制? [英] How to set just one limit for axes in ggplot2 with facets?

查看:47
本文介绍了如何使用刻面为ggplot2中的轴仅设置一个限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与此类似:(v0.3.0)创建于2020-04-30 sup>

通过扩展删除边距.也可以单面.对于连续轴,右边距设置为默认的倍数展开倍数0.05.

  ggplot(vegLengths,aes(length,fill = veg))+geom_density(alpha = 0.2)+scale_x_continuous(expand =扩展(mult = c(0,0.05)))+coord_cartesian(xlim = c(0,NA)) 

This question is similar to this one: How to set limits for axes in ggplot2 R plots?, with the difference that I want to limit one side only (e.g. plot only for x>0 instead of -5000 < x < 5000 ) and do it with facets.

Note, I'd like to know solutions for both of these simple cases:

  1. scale_x_continuous(limits = c(-5000, 5000)) ( the same asxlim(-5000, 5000)) - it removes points entirely from consideration (e.g. they will not be used for geom_smooth())

  2. coord_cartesian(xlim = c(-5000, 5000)) functions - it simply does not plot them (but still uses for geom_smooth())

This situation happens often when you use facet_wrap(~veg, scales = "free_x) and don't know what the upper x limit for each facet, but you know that they are always positive.

解决方案

Set limits one-sided with NA. Works both in coord_ and scale_ functions

I generally prefer coord_ because it does not remove data. For the example below you would additionally need to remove the margin at 0, e.g. with expand.

library(ggplot2)    

carrots <- data.frame(length = rnorm(500000, 10000, 10000))
cukes <- data.frame(length = rnorm(50000, 10000, 20000))
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'
vegLengths <- rbind(carrots, cukes)

ggplot(vegLengths, aes(length, fill = veg)) +
  geom_density(alpha = 0.2) +
  scale_x_continuous(limits = c(0, NA))
#> Warning: Removed 94542 rows containing non-finite values (stat_density).


ggplot(vegLengths, aes(length, fill = veg)) +
  geom_density(alpha = 0.2) +
  coord_cartesian(xlim = c(0, NA))

Created on 2020-04-30 by the reprex package (v0.3.0)

remove the margin with expand. Also one sided possible. the right margin is set to the default mult expansion of 0.05 for continous axis.

ggplot(vegLengths, aes(length, fill = veg)) +
  geom_density(alpha = 0.2) +
  scale_x_continuous(expand = expansion(mult = c(0, 0.05))) +
  coord_cartesian(xlim = c(0, NA))

这篇关于如何使用刻面为ggplot2中的轴仅设置一个限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆