2013-11-14 62 views
10

为了布局原因,我想定位以标签为中心的分段条,使条的中间位于标签顶部。对齐以标签为中心的柱状图条形码

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替代FX)

回答

19

这并不需要一个明确的x轴,但你要玩一点点,如果你有不同的装仓宽度大于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( < 2.1.0),使用geom_histogram(binwidth=1, origin=-0.5)

+0

的'origin'参数现在已被贬值以支持“边界”,如果您使用的是'ggplot2' 2.1或更高版本,则需要使用该参数。 – niczky12

7

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

+0

对不起,但您不必要地介绍了一个新软件包,并且忽略了我不请求geom_bar的请求。调整或删除你的答案。谢谢 – Raffael

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() 
+0

虽然这个答案没有任何解释(也许应该是f滞后?),它有最好的主意 - 使用因素。 –

+0

heh;现在它在ggplot2版本2.1.0中引发错误 –