如何获得ggplot中条形之间的间隙?

时间:2021-04-20 13:48:34

标签: r ggplot2 graph

帮助!

我正在使用 ggplot2 绘制每个月并排的两个值的计数(d1 和 d2)。

我的代码目前生成这样的图表:

enter image description here

但我真的需要每个月在成对的条形之间添加一个空格,以便更清晰地阅读。我已经尝试了很多东西,但无法让它工作。有人可以提出解决方案吗?

答案建议 herehere 生成图,其中条形相互重叠,我收到错误消息“position_dodge 需要不重叠的 x 间隔”。

这是我的代码:

m_scores = ddply(data_NKsam2,.(zdate),summarise, d1 = sum(d1) , d2 = sum(d2))

require(tidyr)

df <- gather(m_scores, event, total, d1:d2)

plot <- ggplot(df, aes(zdate, total, fill=event))
plot <- plot + geom_bar(stat = "identity", position = 'dodge')

这是数据“m_scores”的一部分

  zdate  d1   d2
11 Nov 2014 263  318
12 Dec 2014 430  662
13 Jan 2015 507  326
14 Feb 2015 326  279
15 Mar 2015 281  345
16 Apr 2015 352  260
17 May 2015 280  315
18 Jun 2015 243  238
19 Jul 2015 313  251
20 Aug 2015 446  439
21 Sep 2015 416  404
22 Oct 2015 616  423
23 Nov 2015 269  242
24 Dec 2015 781  527
25 Jan 2016 865  861
26 Feb 2016 997 2139
27 Mar 2016 920 1421
28 Apr 2016 376  498
29 May 2016 434  309
30 Jun 2016 271  284

或者在这里,我尝试使用 dput() 来复制它:

structure(list(zdate = structure(c(2014, 2014.08333333333, 2014.16666666667, 
2014.25, 2014.33333333333, 2014.41666666667, 2014.5, 2014.58333333333, 
2014.66666666667, 2014.75, 2014.83333333333, 2014.91666666667, 
2015, 2015.08333333333, 2015.16666666667, 2015.25, 2015.33333333333, 
2015.41666666667, 2015.5, 2015.58333333333), class = "yearmon"), 
    d1 = c(2, 5, 2, 2, 3, 3, 5, 8, 3, 158, 263, 430, 507, 326, 
    281, 352, 280, 243, 313, 446), d2 = c(0, 3, 5, 1, 3, 2, 0, 
    1, 2, 131, 318, 662, 326, 279, 345, 260, 315, 238, 251, 439
    )), row.names = c(NA, 20L), class = "data.frame")

非常感谢任何人可以提供的任何帮助!

1 个答案:

答案 0 :(得分:1)

您可以设置 width 参数。这控制了躲避条的总数(在中间创建空间)。在此处查看对绘图线的修订:

plot + geom_bar(stat = "identity", position = 'dodge')

enter image description here

并使用 width 参数集:

plot + geom_bar(stat = "identity", position = 'dodge', width=0.5)

enter image description here