将直方图条对齐在标签上

时间:2013-11-14 21:56:29

标签: r ggplot2

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

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)

这是它到目前为止的样子 - 栏的左侧是标签的顶部:

enter image description here

是否可以以这种方式调整给定的片段? (不使用geom_bar而不是f.x。)

3 个答案:

答案 0 :(得分:19)

这不需要分类的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(&lt; 2.1.0),请使用geom_histogram(binwidth=1, origin=-0.5)

答案 1 :(得分:8)

以下是一个选项:计算您自己的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)

enter image description here

答案 2 :(得分:5)

下面的代码曾经工作但不再工作。它阻止了ggplot假设垃圾箱可以均匀分割(但现在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 ()
相关问题