限制ggplot2轴而不移除数据(外部限制):缩放 [英] Limit ggplot2 axes without removing data (outside limits): zoom

查看:146
本文介绍了限制ggplot2轴而不移除数据(外部限制):缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在ggplot中指定了轴限制,则会移除离群点。这对点很好,但是你可能想绘制与指定范围相交的线,但ggplot的范围 xlim / ylim 方法删除这些。有没有另外一种方法来指定绘图轴范围而不删除离群数据?

eg

  require(ggplot2)
d = data.frame(x = c(1,4,7,2,9,7),y = c(2,5,4,10,5,3 ),grp = c('a','a','b','b','c','c'))
ggplot(d,aes(x,y,group = grp)) + geom_line()
ggplot(d,aes(x,y,group = grp))+ geom_line()+ scale_y_continuous(limits = c(0,7))
ggplot(d,aes(x ,y,group = grp))+ geom_line()+ ylim(0,7)


解决方案

哈德利在第99页解释了这一点;他的 ggplot2书(第1版)如果您有第二版,请参阅第160-161页



问题在于,如果您在比例尺内设置 limits 或设置 ylim 会导致数据被丢弃,因为它们正在限制数据。对于真实缩放(保留所有数据),您需要在笛卡尔坐标系内设置限制。欲了解更多信息,请参阅: http://docs.ggplot2.org/current/coord_cartesian.html


$ b $

  ggplot(d,aes(x,y,group = grp))+ geom_line()+ 
coord_cartesian ylim = c(0,7))


If you specify axis limits in ggplot the outlying points are removed. This is fine for points, but you might want to plot lines that intersect with the specified range, but ggplot's range or xlim/ylim methods removes these. Is there another way to specify the plot axis range without removing outlying data?

e.g.

require(ggplot2)
d = data.frame(x=c(1,4,7,2,9,7), y=c(2,5,4,10,5,3), grp=c('a','a','b','b','c','c'))
ggplot(d, aes(x, y, group=grp)) + geom_line()
ggplot(d, aes(x, y, group=grp)) + geom_line() + scale_y_continuous(limits=c(0,7))
ggplot(d, aes(x, y, group=grp)) + geom_line() + ylim(0,7)

解决方案

Hadley explains this on pp. 99; 133 of his ggplot2 book (1st edition), or pp. 160 - 161 if you have the second edition

The issue is that as you say limits inside the scale or setting ylim causes data to be thrown away, as they are constraining the data. For a true zoom (keep all the data), you need to set the limits inside of the Cartesian coordinate system. For more see: http://docs.ggplot2.org/current/coord_cartesian.html

ggplot(d, aes(x, y, group=grp)) + geom_line() + 
    coord_cartesian(ylim=c(0, 7))

这篇关于限制ggplot2轴而不移除数据(外部限制):缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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