【问题标题】:How to plot histogram/ frequency-count of a vector with ggplot?如何用ggplot绘制向量的直方图/频率计数?
【发布时间】:2013-10-02 06:32:45
【问题描述】:

我想用 ggplot 绘制数值向量中值的频率。使用plot() 非常简单,但使用 ggplot 无法获得相同的结果。

library(ggplot2)    
dice_results <- c(1,3,2,4,5,6,5,3,2,1,6,2,6,5,6,4)    
hist(dice_results)

ggplot(dice_results) + geom_bar()
# Error: ggplot2 doesn't know how to deal with data of class numeric

我应该为ggplot() 创建一个数据框来绘制我的向量吗?

【问题讨论】:

    标签: r vector ggplot2 histogram


    【解决方案1】:

    请查看帮助页面?geom_histogram。从第一个示例中,您可能会发现这是可行的。

    qplot(as.factor(dice_results), geom="histogram")
    

    另请查看?ggplot。你会发现数据必须是data.frame

    【讨论】:

      【解决方案2】:

      试试下面的代码

      library(ggplot2)    
      dice_results <- c(1,3,2,4,5,6,5,3,2,1,6,2,6,5,6,4,1,3,2,4,6,4,1,6,3,2,4,3,4,5,6,7,1)
      ggplot() + aes(dice_results)+ geom_histogram(binwidth=1, colour="black", fill="white")
      

      【讨论】:

        【解决方案3】:

        出现错误的原因是参数名称错误。如果您没有明确提供参数名称,则使用顺序规则 - data arg 用于输入向量。

        要更正它 - 明确使用 arg 名称:

        ggplot(mapping = aes(dice_results)) + geom_bar()
        

        您可以在 geom_ 函数家族中使用它,而无需显式命名 mapping 参数,因为 mapping 是第一个参数,这与 ggplot 函数情况不同,data 是第一个函数参数。

        ggplot() + geom_bar(aes(dice_results))
        

        使用geom_histogram 代替geom_bar 绘制直方图:

        ggplot() + geom_histogram(aes(dice_results))
        

        不要忘记使用 bins = 5 覆盖不适合当前情况的默认 30:

        ggplot() + geom_histogram(aes(dice_results), bins = 5)
        
        qplot(dice_results, bins = 5) # `qplot` analog for short
        

        要重现基本hist 绘图逻辑,请使用中断参数代替强制整数(自然)数字用于中断值:

        qplot(dice_results, breaks = 1:6)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-08-09
          • 2017-08-25
          • 1970-01-01
          • 1970-01-01
          • 2017-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多