【问题标题】:Align bars of histogram centered on labels对齐以标签为中心的直方图条
【发布时间】:2013-11-14 21:56:29
【问题描述】:

出于布局原因,我想将直方图条放置在标签的中心位置,这样条的中间就位于标签的顶部。

library(ggplot2)

df <- data.frame(x = c(0,0,1,2,2,2))

ggplot(df,aes(x)) + 
    geom_histogram(binwidth=1) + 
    scale_x_continuous(breaks=0:2)

这是目前的样子 - 条的左侧位于标签的顶部:

是否可以通过这种方式调整给定的 sn-p? (不使用 geom_bar 代替 f.x.)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这不需要一个分类的 x 轴,但如果你的 bin 宽度不同于 1,你会想玩一点。

    library(ggplot2)
    
    df <- data.frame(x = c(0,0,1,2,2,2))
    
    ggplot(df,aes(x)) + 
    geom_histogram(binwidth=1,boundary=-0.5) + 
    scale_x_continuous(breaks=0:2)
    

    对于较旧的ggplot2 (geom_histogram(binwidth=1, origin=-0.5)。

    【讨论】:

    • origin 参数现已贬值,取而代之的是 boundary。如果您使用的是ggplot2 2.1 或更高版本,则需要使用它。
    【解决方案2】:

    这是一种选择:计算您自己的 y 值,使用 x 作为分类 x 轴并使用 geom_bar(stat="identity")

    library(ggplot2)
    library(data.table)
    
    df = data.table(x = c(0,0,1,2,2,2))
    
    df = df[, .N, by=x]
    
    p = ggplot(df, aes(x=factor(x), y=N)) +
        geom_bar(stat="identity", width=1.0)
    
    ggsave("barplot.png", p, width=8, height=4, dpi=120)
    

    【讨论】:

    • 抱歉,您不必要地引入了一个新软件包,并且忽略了我不使用 geom_bar 的请求。请调整或删除您的答案。谢谢
    【解决方案3】:

    下面的代码曾经可以工作,但现在不行了。它阻止了 ggplot 假设 bin 可以被平均划分(但现在 ggplot2::geom_hiustogram 抓住了这个诡计并建议使用不同的函数:

    ggplot(df,aes( factor(x) )) + 
        geom_histogram(binwidth=1 )
    #Error: StatBin requires a continuous x variable the x variable is discrete. Perhaps you want stat="count"?
    

    所以改为使用:

    ggplot(df,aes( factor(x) )) + 
        stat_count ()
    

    【讨论】:

    • 虽然这个答案没有任何解释(也许应该被标记?),它有最好的想法——使用因素。
    • 嘿;现在它在 ggplot2 版本 2.1.0 中引发错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多