R:ggplot2画图坐标系调整——ylim与coord_car

2022-06-15  本文已影响0人  纵纵纵小鸮

       使用ggplot2画图时,有时会需要修改坐标轴范围,有两种方法均可以修改:xlim/ylim和coord_cartesian,但二者的结果可能会截然不同。

        例如在使用geom_density画核密度图时,使用ylim限定坐标轴时图如下:

    使用coord_cartesian调整坐标轴时图如下:

       可以看到,在使用xlim/ylim调整坐标轴时,最下面棕色的线没有峰,而在第二张图中,棕色线有高峰。原因是ylim调整坐标轴的原理是把超出设置范围内的数据都替换为NA,即范围外的数据会被丢弃,所以在图中就显示接近0的区域缺失。而使用coord_cartesian时不会改变数据,只是改变图像呈现的区域,因此会有上两图的不同,可以根据自己的需求选用合适的方式。

        附lims和Cartesiam的官方介绍:

limits:

This is a shortcut for supplying the limits argument to the individual scales. By default, any values outside the limits specified are replaced with NA. Be warned that this will remove data outside the limits and this can produce unintended results. 

用法:lims(...);xlim(...);ylim(...)

coord-cartesian:

The Cartesian coordinate system is the most familiar, and common, type of coordinate system. Setting limits on the coordinate system will zoom the plot (like you're looking at it with a magnifying glass), and will not change the underlying data like setting limits on a scale will.

用法:

coord_cartesian( xlim = NULL, ylim = NULL, expand = TRUE, default = FALSE, clip = "on" )

上一篇下一篇

猜你喜欢

热点阅读