2
votes

I'm trying to create a bar chart in ggplot2 showing a histogram for a large data set.

ggplot(data = score.data, aes(x = score)) + geom_bar(binwidth = .25, width=.9)

My employer's graphic design policy is to have a small amount of separation between bars. But no matter what I set the width parameter to, the plot is generated with no space between bars whatsoever. Is there a different parameter I should be using to accomplish this?

EDIT: Following jeremycg's suggestion in the comments, I've included some of my data.

score <- c(6.25, 4.75, 6, 1.5, 6, 5, 6, 2.75, 6, 2.5, 5.25, 6, 3.75, 6, 
           6.25, 5, 6.75, 2, 2.75, 3.25, 5.625, 6.5, 4, 5, 3)

I'd convert it to a factor, except I want to show bins of size .25 - there are a small number of values between the quarters (as you can see above, where one value is 5.625). And stat_bin only works for data that ggplot thinks is continuous.

1
The solution depends on the format of your data (factors, numeric, etc). You could try including some of you data in the question - try pasting in the output of dput(head(score.data)). If you have integers as your score, you could try ggplot(data = score.data, aes(x = factor(score))) + geom_bar()jeremycg
See here for a similar question with answer.Axeman
As you haven't responded to my answer yet, I was wondering whether it gave the needed solution for you.Jaap
Yes, that turned out to work well for what I needed to do. Thank you.Empiromancer

1 Answers

3
votes

Supposing you have numeric data and not integers, you can set colour = "white" and size = 1.5 (or another value) in geom_bar or geom_histogram. This will make the edges of the bars white and thicker (with the size parameter), thus creating some visual space between them:

# create some sample data
set.seed(2)
data <- data.frame(score=rnorm(1000,0,5), int.score=sample(1:10,1000,replace=TRUE))

# create the plot
ggplot(data, aes(x = score)) + 
  geom_bar(binwidth = .25, color="white", size=1.5) +
  theme_bw()

this gives:

enter image description here

When you have integers, you can also use the trick metioned by @jeremycg in the comments:

ggplot(data, aes(x = factor(int.score))) + 
  geom_bar(width=0.7) +
  theme_bw()

which gives:

enter image description here