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


R ggplot2 lims 設置規模限製


這是向各個比例提供 limits 參數的快捷方式。默認情況下,任何超出指定限製的值都將替換為 NA 。請注意,這將刪除超出限製的數據,並可能產生意想不到的結果。要在不刪除數據觀測的情況下更改 x 或 y 軸限製,請參閱 coord_cartesian()

用法

lims(...)

xlim(...)

ylim(...)

參數

...

對於xlim()ylim() :兩個數值,指定刻度的左/下限和右/上限。如果先給出較大的值,則比例將相反。如果您想從數據範圍計算相應的限製,可以將一個值保留為NA

對於 lims() :名稱-值對。名稱必須美觀,值必須是長度為 2 的數字、字符、因子或日期/時間。數值將創建連續的比例。如果較大的值先出現,則比例將反轉。如果您想根據數據範圍計算相應的限製,可以將一個值保留為NA。字符或因子值將創建離散比例。日期時間值將創建連續的日期/時間刻度。

也可以看看

要擴展繪圖範圍以始終包含某些值,請參閱 expand_limits() 。對於其他類型的數據,請參閱 scale_x_discrete()scale_x_continuous()scale_x_date()

例子

# Zoom into a specified area
ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  xlim(15, 20)
#> Warning: Removed 19 rows containing missing values (`geom_point()`).


# reverse scale
ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  xlim(20, 15)
#> Warning: Removed 19 rows containing missing values (`geom_point()`).


# with automatic lower limit
ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  xlim(NA, 20)
#> Warning: Removed 14 rows containing missing values (`geom_point()`).


# You can also supply limits that are larger than the data.
# This is useful if you want to match scales across different plots
small <- subset(mtcars, cyl == 4)
big <- subset(mtcars, cyl > 4)

ggplot(small, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() +
  lims(colour = c("4", "6", "8"))


ggplot(big, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() +
  lims(colour = c("4", "6", "8"))


# There are two ways of setting the axis limits: with limits or
# with coordinate systems. They work in two rather different ways.

set.seed(1)
last_month <- Sys.Date() - 0:59
df <- data.frame(
  date = last_month,
  price = c(rnorm(30, mean = 15), runif(30) + 0.2 * (1:30))
)

p <- ggplot(df, aes(date, price)) +
  geom_line() +
  stat_smooth()

p
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'


# Setting the limits with the scale discards all data outside the range.
p + lims(x= c(Sys.Date() - 30, NA), y = c(10, 20))
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
#> Warning: Removed 30 rows containing non-finite values (`stat_smooth()`).
#> Warning: Removed 30 rows containing missing values (`geom_line()`).


# For changing x or y axis limits **without** dropping data
# observations use [coord_cartesian()]. Setting the limits on the
# coordinate system performs a visual zoom.
p + coord_cartesian(xlim =c(Sys.Date() - 30, NA), ylim = c(10, 20))
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'


源代碼:R/limits.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Set scale limits。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。