简体   繁体   English

删除ggplot2 geom_bar中栏之间的空格

[英]Remove space between bars in ggplot2 geom_bar

I am looking to "dodge" the bars of a barplot together. 我希望一起“躲避”一个条形图的酒吧。 The following R code leaves white space between the bars. 以下R代码在条形之间留下空白区域。 Other answers like this one show how to accomplish this for the bars part of a group, but that does not seem to apply for distinct bars per factor on the x axis. 像这样的其他答案显示了如何为组的条形部分实现此目的,但这似乎不适用于x轴上每个因子的不同条形。

require(ggplot2)
dat <- data.frame(a=c("A", "B", "C"), b=c(0.71, 0.94, 0.85), d=c(32, 99, 18))

ggplot(dat, aes(x= a, y = b, fill=d, width = d/sum(d))) +
  geom_bar(position=position_dodge(width = 0.1), stat="identity")

Playing with the width variable changes the appearance, but it does not seem possible to get the bars to sit side by side while still retaining their meaningful difference in width (in this graph redundantly represented by the fill colour too). 使用宽度变量可以改变外观,但似乎不可能让条形并排放置,同时仍然保留它们有意义的宽度差异(在此图中也用填充颜色冗余表示)。

I would generate my x-positions and widths first, then pass them in to the aesthetics and override to make your factor labels: 我会首先生成我的x位置和宽度,然后将它们传递到美学并覆盖以使您的因子标签:

First, store the width 首先,存储宽度

dat$width <-
  dat$d / sum(dat$d)

Then, assuming that your data.frame is in the order you want it plotted, you can set the location as the cumulative sum of the widths. 然后,假设您的data.frame按照您希望绘制的顺序排列,您可以将位置设置为宽度的累积和。 Note, however, that that cumulative sum is where you want the right edge of the bar to be, so to get the center you need to subtract half of the width: 但请注意,累积总和是您想要条形右边缘的位置,因此要获得中心,您需要减去宽度的一半:

dat$loc <-
  cumsum(dat$width) - dat$width/2

Then, pass it all in to the ggplot call, setting your labels explictly: 然后,将其全部传递给ggplot调用, ggplot设置标签:

ggplot(dat, aes(x= loc, y = b, fill=d, width = width)) +
  geom_bar(stat="identity") +
  scale_x_continuous(breaks = dat$loc
                     , labels = dat$a)

gives

在此输入图像描述

I am not sure about the advisability of this appproach, but this should get the job done. 我不确定这个appproach的可行性,但这应该完成工作。

It is possible by using a continuous x axis and relabel it. 可以使用连续的x轴并重新标记它。

ggplot(dat, aes(x=cumsum(d/sum(d))) - d/sum(d)/2, y = b, fill=d, width=d/sum(d))) +
  geom_bar(stat="identity", position=position_dodge()) +
  scale_x_continuous(breaks=cumsum(dat$d/sum(dat$d)) - dat$d/sum(dat$d)/2, labels=dat$a)

Or isn't this what you where looking for 或者这不是你在寻找的地方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM