【问题标题】:Grouped histogram based on range in R基于R中范围的分组直方图
【发布时间】:2021-08-21 20:40:15
【问题描述】:

我有一个这种格式的数据集,我想制作一个分组直方图和范围,即10-20, 20-30, ..., 90-100

   group weight
1  A     54
2  A     55
3  B     52
4  B     53
5  C     60

我尝试了以下方法来生成直方图,但不确定如何在 X 轴上制作权重范围。

ggplot(df, aes(x = weight)) +
  geom_histogram(aes(color = gp), fill = "white",
                 position = "identity", bins = 30) +
  scale_color_manual(values = c("red", "blue", 'green'))

我实际上需要一个像下面这样的直方图

【问题讨论】:

    标签: r ggplot2 histogram


    【解决方案1】:

    这是条形图,不是直方图。这是一种重现它的方法:

    library(dplyr)
    
    df %>%
      mutate(weight_class = cut(weight,
                                breaks = seq(20, 60, by = 10))) %>%
      ggplot() +
        geom_bar(aes(x = weight_class, fill = group), position = "dodge") +
        scale_fill_manual(values = c("red", "blue", "green"))
    
    

    【讨论】:

    • 它给出了以下错误Error in cut(weight, breaks = seq(20, 60, by = 10)) : object 'weight' not found
    • 您的df 对象是否有weight 列?
    • 是的,它确实有一个weight 列。我在 R studio 上执行这样的语法df <- mutate(weight_class = cut(weight, breaks = seq(20, 60, by = 10)))
    • 那行不通。不过你可以拨打df <- mutate(df, weight_class = cut(weight, breaks = seq(20, 60, by = 10)))
    • 谢谢!!当我执行以下 df<- mutate(df, weight_class = cut(weight, breaks = seq(20, 70, by = 10))) ggplot(df) + geom_bar(aes(x = weight_class, fill = gp), position = "dodge") + scale_fill_manual(values = c("red", "blue", "green")) 时,它现在看起来不错
    猜你喜欢
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多