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

在ggplot2中创建新比例

  •  1
  • Alex  · 技术社区  · 8 年前

    我有下面的图,图分位数标签和中断。目前这是手动完成的。

    library(tidyverse)
    mtcars %>% 
      as_tibble() %>%
         ggplot(aes(y = mpg, x = hp, color = factor(cyl))) +
         geom_point() +
      theme(panel.grid.major = element_blank(),
            panel.grid.minor = element_blank(),
            panel.border = element_blank(),
            panel.background = element_blank()) +
      scale_y_continuous(labels = as.numeric(quantile(mtcars$mpg)),
                         breaks = as.numeric(quantile(mtcars$mpg))) +
      scale_x_continuous(labels = as.numeric(quantile(mtcars$hp)),
                         breaks = as.numeric(quantile(mtcars$hp))) 
    

    reprex package (第0.2.0版)。

    我想做一个函数来处理任何数据集。这是一次尝试

    scale_y_quantile <- function(y){
      ggplot2::scale_y_continuous(labels = as.numeric(quantile(y)))
    }
    

    然后我试着用它如下。

    mtcars %>% 
      as_tibble() %>%
         ggplot(aes(y = mpg, x = hp, color = factor(cyl))) +
         geom_point() +
      theme(panel.grid.major = element_blank(),
            panel.grid.minor = element_blank(),
            panel.border = element_blank(),
            panel.background = element_blank()) +
      scale_y_quantile()
    but I get the following error
    

    分位数错误(y):找不到对象“y”

    aes() .

    1 回复  |  直到 8 年前
        1
  •  2
  •   Maurits Evers    8 年前

    我相信这仍然可以优化,但这是一个开始:

    1. quantile_breaks 返回基于 quantile(val)

      # Define function for quantile breaks based on val
      quantile_breaks <- function(val, prob) {
          function(x) as.numeric(quantile(val, prob))
      }
      
    2. 定义变换函数 scales::trans_new 中断定义为

      quantile_trans <- function(val, prob) {
          scales::trans_new(
              name = "quantile",
              transform = function(x) x,
              inverse = function(x) x,
              breaks = quantile_breaks(val, prob))
      }
      
    3. scale_*_quantile 位置刻度。

      scale_x_quantile <- function(val, prob = seq(0, 1, 0.25), ...) {
          scale_x_continuous(..., trans = quantile_trans(val, prob))
      }
      
      scale_y_quantile <- function(val, prob = seq(0, 1, 0.25), ...) {
          scale_y_continuous(..., trans = quantile_trans(val, prob))
      }
      

    让我们测试一下 mtcars :

    mtcars %>%
        ggplot(aes(hp, mpg, colour = factor(cyl))) +
        geom_point() +
        scale_x_quantile(mtcars$hp) +
        scale_y_quantile(mtcars$mpg)
    

    enter image description here

    您还可以更改要显示的分位数,例如显示您可以显示的所有20%(而不是默认的25%四分位数)

    mtcars %>%
        ggplot(aes(hp, mpg, colour = factor(cyl))) +
        geom_point() +
        scale_x_quantile(mtcars$hp, prob = seq(0, 1, 0.2)) +
        scale_y_quantile(mtcars$mpg, prob = seq(0, 1, 0.2))
    

    enter image description here