【问题标题】:Make a new scale in ggplot2在 ggplot2 中创建一个新比例
【发布时间】:2018-08-28 23:40:20
【问题描述】:

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

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 (v0.2.0) 于 2018 年 8 月 28 日创建。

我想创建一个对任何数据集执行此操作的函数。这是一次尝试

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() 的数据。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

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

    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_breaks 定义中断。

      quantile_trans <- function(val, prob) {
          scales::trans_new(
              name = "quantile",
              transform = function(x) x,
              inverse = function(x) x,
              breaks = quantile_breaks(val, prob))
      }
      
    3. 定义 2 个新的 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)
    

    您还可以更改要显示的分位数,例如要显示所有 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))
    

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      相关资源
      最近更新 更多