在ggplot中移动了条形图

时间:2017-01-25 20:39:43

标签: r ggplot2 count frequency

我在ggplot中创建了一个条形图,以显示列scheme中的计数如何随时间变化(即从2001年到2016年)。

x轴是year,y轴显示频率(我使用fill=)来获取计数。

数据集由两列(yearscheme)组成,填充了字符值:

year scheme

2016 yes
2016 yes
2016 yes
2016 yes
2015 yes
2015 yes
2014 yes
2013 yes
....
2006 no
2006 no
2006 no
2006 no
2005 no
2005 no
2004 no
2003 no
2002 no
2002 no
2001 no
2001 no

我的代码:

a <- ggplot(s) + 
    stat_bin(aes(x=year, fill=scheme, group=scheme), geom="bar", position = "dodge",bins=30)
b <- a + scale_x_continuous(breaks = c(2001:2016), labels = factor(2001:2016))
c <- b + theme(axis.text.x=element_text(size = 10, colour = "black"))

图表:

The bar graph in ggplot

我遇到的问题是条形图无缘无故地在图形中移动。您可以通过查看x轴和year标签来识别它。条形图向左移动(例如,2007)或向右移动(2002)。

我不知道为什么会这样,我该如何解决?任何类型的建议都非常受欢迎。

1 个答案:

答案 0 :(得分:2)

使用binwidth = 1代替bins = 30。当您指定应该有30个分箱时,您要求将年份分解为端点为seq(2001, 2016, length.out = 30)中的连续值的分段。

所有奇怪的差距来自不包含整数的箱子。