【问题标题】:How to set aside certain numeric values of x with ggplot?如何用ggplot留出x的某些数值?
【发布时间】:2018-05-09 09:02:38
【问题描述】:

我有一个连续的刻度,包括一些编码不同类别缺失的值(例如998,999),我想制作一个不包括这些数字缺失值的图。

由于这些值是在一起的,我每次都可以使用xlim,但由于它决定了绘图的域,我必须为每个不同的情况更改值。

然后,我寻求解决方案。我认为有两种可能。

  • 是否可以对 x 值设置不确定的限制?我的意思是,如果我给出 990 作为最大限制,但出现的最大值是 100,则绘图应该显示一个 x 范围,直到大约 100,而不是像 xlim 那样的 990。
  • 是否有与 xlim? 相反的功能,这意味着由限制(或给定的一组离散值)确定的范围不会包含在 x 轴中。

提前致谢。

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    我认为最简单的方法是在 ggplot 调用之前或期间在图中排除这些值。

    MWE

    library(tidyverse)
    
    # Create data with overflowing data
    mtcars2 <- mtcars
    mtcars2[5:15, 'mpg'] <- 998
    
    # Full plot
    mtcars2 %>% ggplot() +
       geom_point(aes(x = mpg, y = disp))
    

    绘图前过滤

    mtcars2 %>% 
       filter(mpg < 250) %>% 
       ggplot() +
       geom_point(aes(x = mpg, y = disp))
    

    绘图期间过滤

    mtcars2 %>% 
       ggplot() +
       geom_point(aes(x = mpg, y = disp), data = . %>% filter(mpg < 250))
    

    【讨论】:

    • 我正在寻找类似您的 Filtering during plot 选项的内容。有用。谢谢!
    • 不客气!这是一个几乎没有记录的功能,但在同一个图中覆盖多个图层通常非常有用(例如标记异常值)。
    【解决方案2】:

    我会从原始数据集中过滤掉那些缺失值:

    library(dplyr)
    
    df <- data.frame(cat = rep(LETTERS[1:4], 3),
                     values = sample(10, 12, replace = TRUE)
    )
    # Add missing values
    df$values[c(1,5,10)] <- 999
    df$values[c(2,7)] <- 998
    
    invalid_values <- c(998, 999)
    
    library(ggplot2)
    
    df %>% 
      filter(!values %in% invalid_values) %>% 
      ggplot() +
      geom_point(aes(cat, values))
    

    或者,如果由于某种原因无法做到这一点,您可以定义比例转换:

    df %>% 
      ggplot() +
      geom_point(aes(cat, values)) +
      scale_y_continuous(trans = scales::trans_new('remove_invalid',
                                                   transform = function(d) {d <- if_else(d %in% invalid_values, NA_real_, d)},
                                                   inverse = function(d) {if_else(is.na(d), 999, d)}
                                                   )
                         )
    #> Warning: Transformation introduced infinite values in continuous y-axis
    #> Warning: Removed 5 rows containing missing values (geom_point).
    

    reprex package (v0.2.0) 于 2018 年 5 月 9 日创建。

    【讨论】:

      猜你喜欢
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多