【问题标题】:R - Grouped histogramR - 分组直方图
【发布时间】:2014-08-15 06:42:35
【问题描述】:

我的 R 有点生锈,我想弄清楚如何制作分组直方图。我想做一个分组直方图,其中 ratio.dis 和 ratio.opt 按“名称”分组。数据如下:

            name total ratio.dis  n ratio.opt
1 bass karen    13  2.000000  5  2.600000
2     braley    48  2.562500 16  3.000000
3        chu    18  2.166667  6  3.000000
4  cicilline    18  2.500000  6  3.000000
5    clinton    56  2.000000 18  3.111111
6    conyers    54  2.555556 18  3.000000

所有其他关于分组变量的教程都使用 ggplot 并通过“填充”分组变量,但这在这里不起作用,因为每个分类变量只有一个值。在我希望创建的直方图中,“名称”是 X 值,两个比率变量共享相同的 y 轴。我该怎么做?

【问题讨论】:

  • 一些不错的解决方案here.
  • @tom:您的反馈将不胜感激。

标签: r graph histogram


【解决方案1】:

以下可能会有所帮助:

ddf = structure(list(name = c("bass.karen", "braley", "chu", "cicilline", 
"clinton", "conyers"), total = c(13L, 48L, 18L, 18L, 56L, 54L
), ratio.dis = c(2, 2.5625, 2.166667, 2.5, 2, 2.555556), n = c(5L, 
16L, 6L, 6L, 18L, 18L), ratio.opt = c(2.6, 3, 3, 3, 3.111111, 
3)), .Names = c("name", "total", "ratio.dis", "n", "ratio.opt"
), class = "data.frame", row.names = c(NA, -6L))

ddf2 = melt(ddf[,c(1,3,5)], id='name')

ggplot(ddf2, aes(x=name, y=value, fill=variable))+geom_bar(stat='identity', position='dodge')

【讨论】:

    【解决方案2】:

    一个(非常简单的)基础 R 解决方案:

    dd <- structure(list(name = c("bass.karen", "braley", "chu", "cicilline", 
    "clinton", "conyers"), total = c(13L, 48L, 18L, 18L, 56L, 54L
    ), ratio.dis = c(2, 2.5625, 2.166667, 2.5, 2, 2.555556), n = c(5L, 
    16L, 6L, 6L, 18L, 18L), ratio.opt = c(2.6, 3, 3, 3, 3.111111, 
    3)), .Names = c("name", "total", "ratio.dis", "n", "ratio.opt"
    ), class = "data.frame", row.names = c(NA, -6L))
    
    ddd <- cbind(dd$ratio.dis, dd$ratio.opt)
    rownames(ddd) <- dd$name
    
    barplot(t(ddd), beside = TRUE)
    

    注意barplot返回每个条的中心位置,这样你就可以做类似的事情

    bp <- barplot(t(ddd), beside = TRUE)
    text(bp, as.vector(t(ddd)) + 0.2, c("dis", "opt"), xpd = T)
    

    【讨论】:

    • 不确定你的意思。
    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2020-11-08
    • 2020-05-24
    • 2018-02-03
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多