當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。