首页 > 解决方案 > 覆盖 ggplot 的范围以指示正确的中断

问题描述

我想为ggplot()函数设置限制和中断。我能够做到这一点,但是,在某些情况下ggplot()会覆盖它并且不会产生正确的输出。但是,显式更改休息次数,工作,如果不需要,这将是最好的。

这不起作用:

library(ggplot2)

my_data <- data.frame(x = c(302, 116, 10, 11),
                      y = letters[1:4])

ggplot(my_data,
       aes(x = x,
           y = y)) +
  geom_col() +
  scale_x_continuous(breaks = function(x) pretty(x),
                     limits = function(x) range(pretty(x)))

这有效:

ggplot(my_data,
       aes(x = x,
           y = y)) +
  geom_col() +
  scale_x_continuous(breaks = function(x) pretty(x, 6),
                     limits = function(x) range(pretty(x, 6)))

最后一个似乎没有必要,因为pretty()在两种情况下的输出都是相同的:

pretty(my_data[['x']])

0 50 100 150 200 250 300 350

或者

pretty(my_data[['x']], 6)

0 50 100 150 200 250 300 350

在会话信息下方。

R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server 2012 R2 x64 (build 9600)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252 
[2] LC_CTYPE=English_United Kingdom.1252   
[3] LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_3.3.5

loaded via a namespace (and not attached):
 [1] fansi_0.5.0      digest_0.6.27    withr_2.4.2      dplyr_1.0.7     
 [5] crayon_1.4.1     utf8_1.2.2       grid_4.1.1       R6_2.5.1        
 [9] lifecycle_1.0.0  gtable_0.3.0     magrittr_2.0.1   scales_1.1.1    
[13] pillar_1.6.2     rlang_0.4.11     farver_2.1.0     generics_0.1.0  
[17] vctrs_0.3.8      fortunes_1.5-4   ellipsis_0.3.2   tools_4.1.1     
[21] glue_1.4.2       purrr_0.3.4      munsell_0.5.0    compiler_4.1.1  
[25] pkgconfig_2.0.3  colorspace_2.0-2 tidyselect_1.1.1 tibble_3.1.4 

标签: rggplot2

解决方案


推荐阅读