限制ggplot2轴而不删除数据(外部限制):缩放

问题描述 投票:80回答:1

如果在ggplot中指定轴限制,则删除外围点。这对于点来说很好,但是您可能想要绘制与指定范围相交的线,但是ggplot的rangexlim/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)
r ggplot2 zoom limits
1个回答
134
投票

哈德利在第99页解释了这一点;如果你有ggplot2 book (1st edition),他的second edition中的133,或第160-161页。

问题是,正如你所说,limits在规模或设置ylim()内会导致数据丢失,因为它们限制了数据。对于真正的缩放(保留所有数据),您需要在笛卡尔坐标系(或其他坐标系https://ggplot2.tidyverse.org/reference/#section-coordinate-systems)内设置限制。欲了解更多信息,请访问:http://docs.ggplot2.org/current/coord_cartesian.html

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

© www.soinside.com 2019 - 2024. All rights reserved.