0

I have the dataset with values for different keys for three independent groups and I would like to create a bar plot with these values for 3 different groups using facet_grid. This is what I did so far, however I can not find the way to fix spacing between the bars (it is clearly observed form the picture that they are different). I tried changing arguments width and position for geom_col, but it did not help. How can I fix it?

library(ggplot2)
# Loading

groups = c(rep("q", 8), rep("w", 8), rep("e", 8))
keys = c(c(1:8), c(1:8), c(1:8))
values = c(rep(8, 8), rep(8, 8), rep(8, 8))
data = data.frame(groups, values, keys)

ggplot(data, aes(x = keys, y = values)) +
  geom_col(width=0.9375) +
  facet_grid(~groups)

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nadya
  • 3
  • 2

2 Answers2

0

Try this:

ggplot(data) + 
  geom_bar(aes(x = keys, y = values), stat = "identity") +
  facet_grid(~groups)

enter image description here

Leonardo
  • 2,439
  • 33
  • 17
  • 31
  • I modified my answer by adding the graph and as you can see the columns are equally spaced. Your problem may be due to display only. Try to enlarge the image to the whole screen or something like that – Leonardo Feb 02 '21 at 13:40
  • yes, thank you. The problem was with the resolution of the image. – Nadya Feb 02 '21 at 14:07
  • very well! If the answer was useful to you, if you want accept it – Leonardo Feb 02 '21 at 14:09
0

My guess is that it is an issue with the size/resolution of the image. If the size/resolution is small, you may get this result. Your image is 614 x 362 and @Leonardo is 1362x699. My guess is that this is what is causing this weird spacing.

g <- ggplot(data, aes(x = keys, y = values)) +
  geom_col() + facet_grid(~groups)

png(filename = "Rplotsmall.png", width=614, height = 362)
print(g)
dev.off()

png(filename = "Rplotlarge.png", width=1362, height = 699)
print(g)
dev.off()

Small image (with weird spacing):

enter image description here

Large image (spacing appears ok): enter image description here

If you are using Rstudio and printing to the plot window, you should see this weird effect appear and disappear when you click "zoom" and increase or reduce the size of the window (because then Rstudio is redrawing the image with different size).

kikoralston
  • 1,176
  • 5
  • 6