乱世@小熊 2010-08-22 13:54 采纳率: 25%
浏览 1482
已采纳

如何在 r 中绘制两个直方图?

我正在使用R,并且有两个数据框:胡萝卜和黄瓜。 每个数据框都有一个数字列,其中列出了所有测得的胡萝卜(总计:100k胡萝卜)和黄瓜(总计:50k黄瓜)的长度。 我希望在同一图上绘制两个直方图-胡萝卜长度和黄瓜长度。 它们是重叠的,所以我想我也需要一些透明度。 我还需要使用相对频率而不是绝对数字,因为每个组中的实例数量不同。 像这样的东西会很好,但是我不明白该如何从我的两个表中创建它:

overlapped density

转载于:https://stackoverflow.com/questions/3541713/how-to-plot-two-histograms-together-in-r

  • 写回答

8条回答 默认 最新

  • ~Onlooker 2010-08-22 15:51
    关注

    That image you linked to was for density curves, not histograms.

    If you've been reading on ggplot then maybe the only thing you're missing is combining your two data frames into one long one.

    So, let's start with something like what you have, two separate sets of data and combine them.

    carrots <- data.frame(length = rnorm(100000, 6, 2))
    cukes <- data.frame(length = rnorm(50000, 7, 2.5))
    
    #Now, combine your two dataframes into one.  First make a new column in each that will be a variable to identify where they came from later.
    carrots$veg <- 'carrot'
    cukes$veg <- 'cuke'
    
    #and combine into your new data frame vegLengths
    vegLengths <- rbind(carrots, cukes)
    

    After that, which is unnecessary if your data is in long formal already, you only need one line to make your plot.

    ggplot(vegLengths, aes(length, fill = veg)) + geom_density(alpha = 0.2)
    

    enter image description here

    Now, if you really did want histograms the following will work. Note that you must change position from the default "stack" argument. You might miss that if you don't really have an idea of what your data should look like. A higher alpha looks better there. Also note that I made it density histograms. It's easy to remove the y = ..density.. to get it back to counts.

    ggplot(vegLengths, aes(length, fill = veg)) + 
       geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')
    

    enter image description here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。