代码之家  ›  专栏  ›  技术社区  ›  tassones

如何翻转geom_boxplot并重新缩放轴?

  •  1
  • tassones  · 技术社区  · 2 年前

    我有一个正在使用的方框图 coord_flip() 。我还试图使用 coord_cartesian() 但当我这样做时,方框图就不再翻转了。我一直在听这个短语 Coordinate system already present. Adding new coordinate system, which will replace the existing one. 每次我试着做方框图的时候。如何翻转方框图并重新缩放x轴?

    注意:我也尝试过使用 coord_fixed() 代替 坐标_笛卡尔() 重新缩放,但这也不起作用。

    实例

    library(ggplot2)
    #> Warning: package 'ggplot2' was built under R version 4.2.3
    library(dplyr)
    #> Warning: package 'dplyr' was built under R version 4.2.3
    #> 
    #> Attaching package: 'dplyr'
    #> The following objects are masked from 'package:stats':
    #> 
    #>     filter, lag
    #> The following objects are masked from 'package:base':
    #> 
    #>     intersect, setdiff, setequal, union
    
    # Load the mtcars dataset
    data(mtcars)
    
    data <- mtcars %>%
      select(mpg,cyl)
    
    # Add outliers to specific groups
    outliers <- data.frame(
      mpg = c(45,50,55,45,50,55),
      cyl = c(4,4,4,8,8,8))
    
    # Create example dataset
    data <- rbind(data, outliers)
    
    # Flip axis and show outliers
    data %>%
      ggplot(aes(x = factor(cyl), y = mpg)) +
      geom_boxplot() +
      coord_flip()
    

     
    # Attempt to flip axis and rescale x-axis to not show outliers
    data %>%
      ggplot(aes(x = factor(cyl), y = mpg)) +
      geom_boxplot(outlier.shape = NA) +
      coord_flip() +
      coord_cartesian(xlim=c(0, 45))
    #> Coordinate system already present. Adding new coordinate system, which will
    #> replace the existing one.
    

    
    # Attemp to flip axis and rescale x-axis to not show outliers
    # Perhaps xlim should ylim?
    data %>%
      ggplot(aes(x = factor(cyl), y = mpg)) +
      geom_boxplot(outlier.shape = NA) +
      coord_flip() +
      coord_cartesian(ylim=c(0, 45))
    #> Coordinate system already present. Adding new coordinate system, which will
    #> replace the existing one.
    

    创建于2023-06-23 reprex v2.0.2

    0 回复  |  直到 2 年前
        1
  •  1
  •   Mark    2 年前

    Dave2e 说,使用 ylim (和/或 xlim )要更改图形区域的限制:

    library(tidyverse)
    
    outliers <- data.frame(
      mpg = c(45,50,55,45,50,55),
      cyl = c(4,4,4,8,8,8))
    
    mtcars %>%
      select(mpg,cyl) %>%
        bind_rows(outliers)  %>%
        ggplot(aes(x = factor(cyl), y = mpg)) +
        geom_boxplot() +
        coord_flip(xlim = c(0, 5), ylim = c(0,50))
    
    # Below is what I liked, but you can move things however you want by changing the values of xlim and ylim. Go nuts!
    

    boxplot with strange borders

    信用 Dave2e

    推荐文章