限制 ggplot2 轴而不删除数据(超出限制):缩放 [英] Limit ggplot2 axes without removing data (outside limits): zoom
问题描述
如果您在 ggplot 中指定轴限制,则外围点将被删除.这对于点来说很好,但是您可能想要绘制与指定范围相交的线,但是 ggplot 的 range
或 xlim/ylim
方法会删除这些线.是否有另一种方法可以在不删除外围数据的情况下指定绘图轴范围?
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?
例如
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 在第 99 页解释了这一点;他的 ggplot2 书籍(第一版)中的 133 部 或第 160 - 161 页,如果您有 第二版.
Hadley explains this on pp. 99; 133 of his ggplot2 book (1st edition), or pp. 160 - 161 if you have the second edition.
问题是,正如你所说,limits
在比例或设置 ylim()
导致数据被丢弃,因为它们限制了数据.对于真正的缩放(保留所有数据),您需要在笛卡尔坐标系(或其他坐标系 https://ggplot2.tidyverse.org/reference/#section-coordinate-systems).更多信息请参见:http://docs.ggplot2.org/current/coord_cartesian.html
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 (or other coordinate systems https://ggplot2.tidyverse.org/reference/#section-coordinate-systems). 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屋!