erc
erc

Reputation: 10133

Preventing incosistent spacing/bar widths in geom_bar with many bars

In a bar plot with lots of bars the problem occurs that the spacing between bars and/or the widths of the bars becomes incosistent, also changing with changing the width of the plot.

set.seed(23511)
dat <- data.frame(x = 1:540, y = rnorm(540))

library(ggplot2)
ggplot(dat) +
  geom_bar(aes(x = x, y = y), stat = "identity")

Is there a way to solve this? I tried playing with width and the overall plot size to no avail.

enter image description here

In response to alistaire's comment here's a screenshot of the first few bars from RStudio. Looking at the first 10 values..

    x          y
1   1  0.9450960
2   2  0.9277378
3   3  0.4371033
4   4 -1.0333073
5   5  2.0473397
6   6  0.8174123
7   7  0.4277842
8   8 -0.4336887
9   9  0.2156801
10 10  0.4918345

.. to me it clearly looks like for the first 3 positive values there's space between the bars/the bars are narrower than for the second set of 3 positive values where there's no space between the bars/the bars are wider.

enter image description here

Upvotes: 5

Views: 517

Answers (1)

timcdlucas
timcdlucas

Reputation: 1364

I think this is a pixel issue. If the x of a bar goes from 1.5 to 2.7 pixels, it will be one pixel wide, if it goes from 1.9 to 3.1 (same width) it will be 2 pixels wide.

You could do lines instead of bars.

 ggplot(data=dat, aes(x=x, y=y)) + 
   geom_segment(aes(xend=x, yend=0), size = 0.6) 

I think you still sometimes run into pixel issues, but it's maybe easier to control with size.

Upvotes: 6

Related Questions