出于布局原因,我想将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)
Run Code Online (Sandbox Code Playgroud)
这是它到目前为止看起来的东西 - 酒吧的左侧是标签的顶部:

是否有可能以这种方式调整给定的片段?(不使用geom_bar而不是fx)
col*_*oll 19
这不需要分类的x轴,但如果你有不同的bin宽度,你会想要播放一点.
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)
Run Code Online (Sandbox Code Playgroud)
对于较旧的ggplot2(<2.1.0),请使用geom_histogram(binwidth=1, origin=-0.5).
这是一个选项:计算您自己的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)
Run Code Online (Sandbox Code Playgroud)

紧接下面的代码曾经工作但不再工作.它阻止了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"?
Run Code Online (Sandbox Code Playgroud)
所以改为使用:
ggplot(df,aes( factor(x) )) +
stat_count ()
Run Code Online (Sandbox Code Playgroud)