【问题标题】:How to do multiboxplot for a single variable based on bins from cut function in r?如何根据 r 中 cut 函数的 bin 为单个变量做 multiboxplot?
【发布时间】:2020-12-17 02:57:23
【问题描述】:

我正在尝试为变量创建一个多箱图基于剪切函数的箱数

movie_reg %>% select(Collection) %>% pull() %>% cut(7) 

[1] (3.57e+04,4.86e+04] (3.57e+04,4.86e+04] (6.14e+04,7.43e+04] (6.14e+04,7.43e+04] (6.14e+04,7.43e+04]
  [6] (4.86e+04,6.14e+04] (3.57e+04,4.86e+04] (3.57e+04,4.86e+04] (2.29e+04,3.57e+04] (3.57e+04,4.86e+04]
 [11] (2.29e+04,3.57e+04] (3.57e+04,4.86e+04] (3.57e+04,4.86e+04] (3.57e+04,4.86e+04] (3.57e+04,4.86e+04]
.
.
[501] (2.29e+04,3.57e+04] (3.57e+04,4.86e+04] (3.57e+04,4.86e+04] (3.57e+04,4.86e+04] (3.57e+04,4.86e+04]
[506] (3.57e+04,4.86e+04]
7 Levels: (9.91e+03,2.29e+04] (2.29e+04,3.57e+04] (3.57e+04,4.86e+04] (4.86e+04,6.14e+04] ... (8.71e+04,1e+05]

我不确定在箱线图中我将如何准确地将级别和相应的值传递给它。以下是我尝试过但出现错误的方法:

movie_reg %>% select(Collection) %>% pull() %>% cut(7) %>% boxplot(aes(x=levels))
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 'x' must be atomic

【问题讨论】:

    标签: r visualization boxplot binning


    【解决方案1】:

    如果你提供一个可重现的例子会更好,现在很难帮助你。我确实注意到您在 boxplot 函数中使用了美学,但美学是 ggplot 的一部分,而不是基本函数 boxplot()。此外,在多箱图中,您需要提供 x 和 y,所以也许您只需要一个显示每组计数的条形图(只需要一个 x)?

    movie_reg %>% 
      select(Collection) %>% 
      pull() %>% 
      cut(7) %>% 
      ggplot(aes(x=levels)) + 
      geom_bar()
    

    【讨论】:

    • 谢谢,这很有用。使用split function,我试图实现的目标实际上很容易,我刚刚用代码实现了同样的目标:{r} movie_reg %>% select(Collection) %>% pull() %>% range() movie_reg %>% select(Collection) %>% pull() %>% split(f = as.factor(c(0,20000,40000,60000,80000,100000))) %>% boxplot()
    【解决方案2】:

    我认为您将来自基本 R 的 boxplot() 与来自 ggplot2 的 geom_boxplot() 混淆了。无论如何,如果您的问题是关于可视化从cut() 获得的类别,您可以使用以下方法添加列:

    movie_reg = data.frame(Collection = runif(100))
    movie_reg %>% mutate(levels = cut(Collection,7))
    

    使用箱线图:

    boxplot(Collection ~ levels,data=movie_reg %>% mutate(levels = cut(Collection,7)),horizontal=TRUE,las=2,cex.axis=0.6)
    

    或 ggplot2 :

    movie_reg %>% mutate(levels = cut(Collection,7)) %>% ggplot(aes(x=levels,y=Collection)) + geom_boxplot() + coord_flip()
    

    【讨论】:

    • 感谢@StupidWolf 完美地展示了这些示例。我确实混淆了基本情节和 ggplot 并且我没有变异,所以没有得到情节的 x,y 输入。对于这种类型的绘图,拆分功能也很方便,因为它同时保留了值和组。 {r} movie_reg %>% select(Collection) %>% pull() %>% split(f = c(0,20000,40000,60000,80000,100000)) %>% boxplot()
    • 您基本上是通过像这样使用拆分手动将组分配给行..为什么在 1 个命令就可以通过 4 或 5 个管道?
    • 我是 r 新手,正在探索如何实现分布比较。似乎split 没有通过提及箱数来对值进行分组的选项。如果是这种情况,那么我将使用cut function。再次感谢您的帮助!
    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多