减少ggplot2中条形组之间的空间

问题描述 投票:4回答:1

我无法在geom_plot中删除额外的空格侧面组。

我想做Roland在这里实现的目标:Remove space between bars ggplot2但是当我尝试实施他的解决方案时,我收到错误“警告消息:geom_bar()不再有binwidth参数。请改用geom_histogram()。”

我将这行代码添加到我的绘图中(尝试不同的宽度):

  geom_histogram(binwidth = 0.5) +

返回“错误:stat_bin()不得与y审美一起使用。”没有情节。

数据:

mydf<- data.frame(Treatment = c("Con", "Con", "Ex", "Ex"),
             Response = rep(c("Alive", "Dead"), times=2),
             Count = c(259,10,290,21))

 aPalette<-c("#009E73", "#D55E00")

情节:

example<-ggplot(mydf, aes(factor(Response), Count, fill = Treatment)) + 
  geom_bar(stat="identity",position = position_dodge(width = 0.55), width = 
  0.5) + 
  scale_fill_manual(values = aPalette, name = "Treatment") + #legend title
  theme_classic() +
  labs(x = "Response", 
  y = "Count") + 
  scale_y_continuous(breaks = c(0,50,100,150,200,250,275), expand = c(0,0), 
  limits = c(0, 260)) +
  theme(legend.position = c(0.7, 0.3)) +
  theme(text = element_text(size = 15)) #change all text size

  example

返回:enter image description here

注意:我不知道为什么我收到“警告消息:删除了1行包含缺失值(geom_bar)。”但我不关心它,因为使用我的实际数据不会发生这种情况**编辑重新:注意 - 这是因为我将y轴的限制设置为低于已删除的条的最大值。我不会改为代码所以我不需要重绘我的数字,而是改变

limits = c(0, 260) 

limits = c(0, 300)

将显示所有的酒吧。如果其他人有类似的问题。我将找到一个与此问题相关的帖子,当我可以链接答案时,将使此编辑更简洁

r ggplot2 geom-bar
1个回答
2
投票

请原谅我,如果我完全错过了你想要完成的任务,但ggplot包含如此多空白区域的唯一原因是因为你将条形约束到特定宽度并增加了图形的大小。图表中的空白区域是条形宽度和图形宽度的输出。

使用原始图表... orig graph

我们注意到很多空白,但是你们都把箱子放得很小而你的图表也很宽。将空间视为箱和空白之间的妥协。期望带有小箱子而没有空白的宽图表是不合逻辑的。要解决此问题,我们可以减小图表大小或增加bin大小。

首先,我们通过删除约束来将bin大小恢复正常。哪个看起来很可笑....

enter image description here

但是通过查看上面包含的ggplot2链接之间的删除空间,他所做的就是删除约束并限制宽度。这样做会产生类似的图表......

similar graph

包括上面链接的图表.... enter image description here

并删除所有约束.... enter image description here

    example<-ggplot(mydf, aes(factor(Response), Count, fill = Treatment)) + 
  geom_bar(stat="identity",position = position_dodge()) +
  scale_fill_manual(values = aPalette, name = "Treatment") +
  theme_bw() +
  labs(x = "Response", y = "Count")

example

如果您的目标不是让您的图表与链接中的图表类似,请删除空格让我知道,除此之外,我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.