【问题标题】:ggplot - continuous labels on binned variable?ggplot - 分箱变量上的连续标签?
【发布时间】:2020-09-19 10:12:12
【问题描述】:

让我们看看这两个情节。第一个是由这段代码创建的:

ggplot(iris, aes(x = Petal.Length))+
  stat_bin(geom = "density")

第二张图片类似,由以下代码生成:

library(DescTools)

iris$Petal.Length %>% 
  cut(30) %>% 
  Freq() %>% 
  ggplot(aes(x = level, y = freq, group = 1))+
  geom_line()

由于图像大小,第二张图像中的标签不清晰可见,但它们是虹膜数据的区间(例如(0.994,1.2](1.2,1.39] 等)。

我的问题是:如何将第二个图中的标签更改为与第一个图中的标签完全相同,即首先给人一种从未使用cut 对数据进行分箱的印象。

请不要发布任何涉及不对数据进行分箱并以其他方式生成绘图的解决方案 - 该解决方案需要能够在第二个绘图的代码运行后添加和运行新代码。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    也许这就是你要找的。为了得到一个连续的轴,我提取了区间的下限和上限,转换为数字并计算可以映射到 x 的中心值,并且:

    library(ggplot2)
    library(dplyr)
    library(DescTools)
    
    iris$Petal.Length %>% 
      cut(30) %>% 
      Freq() %>% 
      mutate(lower = stringr::str_match(level, "^.(\\d+\\.\\d+)")[,2],
             upper = stringr::str_match(level, "(\\d+\\.\\d+).$")[,2],
             across(c(lower, upper), as.numeric),
             center = .5 * lower + .5 * upper) %>% 
      ggplot()+
      geom_line(aes(x = center, y = freq, group = 1))
    

    【讨论】:

      【解决方案2】:

      也许这过于简单了。但是使用scale_x_continuous 查看您的问题似乎是最简单的解决方案。 breaks 参数让您指定要显示的刻度线。

      library(DescTools)
      
      iris$Petal.Length %>% 
       cut(30) %>% 
        Freq() %>% 
        ggplot(aes(x = level, y = freq, group = 1))+
        geom_line() +
        scale_x_continuous(breaks = c(2, 4, 6)) +
        labs(x = "Petal.Length", y = "count") 
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-06
        • 2014-02-18
        • 1970-01-01
        • 1970-01-01
        • 2021-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多