当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R ggplot2 coord_cartesian 笛卡尔坐标


笛卡尔坐标系是最熟悉也是最常见的坐标系类型。在坐标系上设置限制将缩放绘图(就像您用放大镜查看它一样),并且不会像在比例上设置限制那样改变基础数据。

用法

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

参数

xlim, ylim

x 轴和 y 轴的限制。

expand

如果 TRUE (默认值)会在限制中添加一个小的扩展因子,以确保数据和轴不重叠。如果 FALSE ,则完全从数据或 xlim /ylim 中获取限制。

default

这是默认的坐标系吗?如果FALSE(默认值),则将此坐标系替换为另一个坐标系会创建一条消息,提醒用户坐标系正在被替换。如果 TRUE ,则该警告被抑制。

clip

是否应该将绘图裁剪到绘图面板的范围内?设置"on"(默认)表示是,设置"off"表示否。在大多数情况下,不应更改 "on" 的默认值,因为设置 clip = "off" 可能会导致意外结果。它允许在绘图上的任何位置绘制数据点,包括绘图边。如果通过 xlimylim 设置限制,并且某些数据点超出这些限制,则这些数据点可能会显示在轴、图例、绘图标题或绘图边距等位置。

例子

# There are two ways of zooming the plot display: with scales or
# with coordinate systems.  They work in two rather different ways.

p <- ggplot(mtcars, aes(disp, wt)) +
  geom_point() +
  geom_smooth()
p
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'


# Setting the limits on a scale converts all values outside the range to NA.
p + scale_x_continuous(limits = c(325, 500))
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
#> Warning: Removed 24 rows containing non-finite values (`stat_smooth()`).
#> Warning: Removed 24 rows containing missing values (`geom_point()`).


# Setting the limits on the coordinate system performs a visual zoom.
# The data is unchanged, and we just view a small portion of the original
# plot. Note how smooth continues past the points visible on this plot.
p + coord_cartesian(xlim = c(325, 500))
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'


# By default, the same expansion factor is applied as when setting scale
# limits. You can set the limits precisely by setting expand = FALSE
p + coord_cartesian(xlim = c(325, 500), expand = FALSE)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'


# Simiarly, we can use expand = FALSE to turn off expansion with the
# default limits
p + coord_cartesian(expand = FALSE)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'


# You can see the same thing with this 2d histogram
d <- ggplot(diamonds, aes(carat, price)) +
  stat_bin2d(bins = 25, colour = "white")
d


# When zooming the scale, the we get 25 new bins that are the same
# size on the plot, but represent smaller regions of the data space
d + scale_x_continuous(limits = c(0, 1))
#> Warning: Removed 17502 rows containing non-finite values (`stat_bin2d()`).
#> Warning: Removed 17 rows containing missing values (`geom_tile()`).


# When zooming the coordinate system, we see a subset of original 50 bins,
# displayed bigger
d + coord_cartesian(xlim = c(0, 1))

相关用法


注:本文由纯净天空筛选整理自Hadley Wickham等大神的英文原创作品 Cartesian coordinates。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。