r - **ggplot2** : Difference between scale_x_continuous(breaks = ) and xlim() (or eqivalently scale_y_continouous(breaks=) and ylim)

标签 r ggplot2

ggplot2中,我想指定图表中的值标签,并使 y 轴和 x 轴处于同一范围内,即使不存在数据也是如此。

基本图p如下所示。我想每 5 个标签添加到 x 轴和 y 轴,并将 x 轴边框扩展到 105,尽管不存在边框。

谁能帮我理解 scale_x_continuous(breaks=...)xlim() 如何交互?或者 scale_x_continuous(breaks=..., lim = c(...)) 有何不同?

library(ggplot2)
library(viridis)
#> Loading required package: viridisLite

ggplot_common_scatter <- function(p, size = 3, step = 1){
  q <- p +
    theme_bw() +
    geom_point(size = size) +
    scale_y_continuous(breaks = h(step)) +
    scale_fill_viridis(begin = 0.4, end = 1, direction = 1, discrete = TRUE) +
    theme(legend.position = "bottom",
          axis.text = element_text(size = 13),      #Text size of axes
          axis.title = element_text(size = 14,face = "plain"),  #Text size of axis titles
          #  axis.text.x = element_text(angle = 90)    #not if text
          #  only for MSD
          panel.grid.major = element_blank(), 
          panel.grid.minor = element_blank(),   #remove gridlines
          legend.box = "horizontal", legend.direction = "vertical"   #add if needed if legend is too wide.
    ) 
  return(q)
}
  
h <- function(k) {
  step <- k
  #  Round the minimum down to the nearest 5
  #  y.min <-  5*floor(min(y)/5
  #  Round the maximum up to the nearest 5
  #  y.max <- 5*ceiling(max(y)/5)
  
  function(y){ 
 #   cat("min: ", min(y, na.rm = TRUE), "max: ", max(y, na.rm = TRUE), "|| Labels:")
    start <- 5*floor(min(y, na.rm = TRUE)/5)
    end <-  5*ceiling(max(y, na.rm = TRUE)/5)
    A <- seq(start, end, by = step)
 #   print(A)
    return(A)
  }
}


data(anorexia, package = "MASS")

p <- ggplot_common_scatter(
  ggplot(anorexia, 
         aes(x = Prewt , 
             y = Postwt, 
             col = Treat,
             pch = Treat 
         )
         ),
         step = 10
  )+
  ggtitle("Comparisons of Aneorxia girls"
  ) +   
  geom_rect(color = "black", fill = NA,  
            aes(xmin = 70, xmax = 100, ymin = 70, ymax = 100)  #lty = "dashed", alpha = 0.5
  )  

p

enter image description here

p + xlim(70, 105)

enter image description here

p + scale_x_continuous(breaks = seq(70, 105, by = 5))

enter image description here

#Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale
p + scale_x_continuous(breaks = seq(70, 105, by = 5)) + xlim(70, 105)
#> Scale for 'x' is already present. Adding another scale for 'x', which will
#> replace the existing scale.

enter image description here

p + scale_x_continuous(breaks = seq(70, 105, by = 5), lim = c(70, 105))

enter image description here

xfun::session_info(c("ggplot2", "viridis"))
#> R version 4.0.4 (2021-02-15)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 18363)
#> 
#> Locale:
#>   LC_COLLATE=English_United States.1252 
#>   LC_CTYPE=English_United States.1252   
#>   LC_MONETARY=English_United States.1252
#>   LC_NUMERIC=C                          
#>   LC_TIME=English_United States.1252    
#> 
#> Package version:
#>   assertthat_0.2.1   cli_2.3.1          colorspace_2.0.0   crayon_1.4.1      
#>   digest_0.6.27      ellipsis_0.3.1     fansi_0.4.2        farver_2.1.0      
#>   ggplot2_3.3.3      glue_1.4.2         graphics_4.0.4     grDevices_4.0.4   
#>   grid_4.0.4         gridExtra_2.3      gtable_0.3.0       isoband_0.2.4     
#>   labeling_0.4.2     lattice_0.20.41    lifecycle_1.0.0    magrittr_2.0.1    
#>   MASS_7.3.53.1      Matrix_1.3.2       methods_4.0.4      mgcv_1.8.34       
#>   munsell_0.5.0      nlme_3.1.152       pillar_1.5.1       pkgconfig_2.0.3   
#>   R6_2.5.0           RColorBrewer_1.1.2 rlang_0.4.10       scales_1.1.1      
#>   splines_4.0.4      stats_4.0.4        tibble_3.1.0       tools_4.0.4       
#>   utf8_1.2.1         utils_4.0.4        vctrs_0.3.6        viridis_0.5.1     
#>   viridisLite_0.3.0  withr_2.4.1
Created on 2021-05-11 by the reprex package (v1.0.0)

最佳答案

警告消息给出提示:

#> Scale for 'x' is already present. Adding another scale for 'x', which will
#> replace the existing scale.

xlim()ylim() 替换图中的现有比例,而不是修改其限制。

下面的代码使用 expand_limits() 修改绘图中已存在的比例限制。 (额外的优势是,如果需要容纳所有观察结果,规模将超过要求的限制。)

p + scale_x_continuous(breaks = seq(70, 105, by = 5)) + 
   expand_limits(x = c(70, 105))

The resulting plot

关于r - **ggplot2** : Difference between scale_x_continuous(breaks = ) and xlim() (or eqivalently scale_y_continouous(breaks=) and ylim),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67487463/

相关文章:

r - 将具有交替缺失值的两个字符串列合并为一个

r - 根据重复行添加频率

R输出相异矩阵

r - 迭代数据框并为每一列创建一个图

r - ggplot2:在不同的方面使用不同的颜色

R ggplot 和分面网格 : how to control x-axis breaks

r - 动态高阶逐行乘积

R - 在预测 ggAcf 图中添加标题

r - 如何在ggplot2中调整 `binwidth`?

r - 基于成功率填充的 stat_bin2d