10

Let's say I want to make a histogram

So I use the following code

v100<-c(runif(100))

v100
library(ggplot2)
private_plot<-ggplot()+aes(v100)+geom_histogram(binwidth = (0.1),boundary=0
)+scale_x_continuous(breaks=seq(0,1,0.1), lim=c(0,1))
private_plot

plot

How do I separate my columns so that the whole thing is more pleasing to the eye?

I tried this but it somehow doesn't work:

Adding space between bars in ggplot2

Thanks

G5W
  • 36,531
  • 10
  • 47
  • 80
Marvin Schopf
  • 141
  • 1
  • 1
  • 11

5 Answers5

15

You could set the line color of the histogram bars with the col parameter, and the filling color with the fill parameter. This is not really adding space between the bars, but it makes them visually distinct.

library(ggplot2)
set.seed(9876)
v100<-c(runif(100))

### use "col="grey" to set the line color
ggplot() +
  aes(v100) +
  geom_histogram(binwidth = 0.1, fill="black", col="grey") +
  scale_x_continuous(breaks = seq(0,1,0.1), lim = c(0,1))

Yielding this graph:

enter image description here

Please let me know whether this is what you want.

KoenV
  • 4,113
  • 2
  • 23
  • 38
7

If you want to increase the space for e.g. to indicate that values are discrete, one thing to do is to plot your histogram as a bar plot. In that case, you have to summarize the data yourself, and use geom_col() instead of geom_histogram(). If you want to increase the space further, you can use the width parameter.

library(tidyverse)
lambda <- 1:6

pois_bar <- 
    map(lambda, ~rpois(1e5, .x)) %>% 
    set_names(lambda) %>% 
    as_tibble() %>% 
    gather(lambda, value, convert = TRUE) %>% 
    count(lambda, value)

pois_bar %>% 
    ggplot() +
    aes(x = value, y = n) +
    geom_col(width = .5) +
    facet_wrap(~lambda, scales = "free", labeller = "label_both")

enter image description here

Tamas Nagy
  • 1,001
  • 12
  • 22
3

Just use color and fill options to distinguish between the body and border of bins:

library(ggplot2)
set.seed(1234)
df <- data.frame(sex=factor(rep(c("F", "M"), each=200)),
                 weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5))))

ggplot(df, aes(x=weight)) + 
geom_histogram(color="black", fill="white")

enter image description here

Gigi
  • 587
  • 5
  • 12
2

In cases where you are creating a "histogram" over a range of integers, you could use:

ggplot(data) + geom_bar(aes(x = value, y = ..count..))
Amadou Kone
  • 907
  • 11
  • 21
1

I just came across this issue. My solution was to add vertical lines at the points separating my bins. I use "theme_classic" and have a white background. I set my bins to break at 10, 20, 30, etc. So I just added 9 vertical lines with:

geom_vline(xintercept=10, linetype="solid", color = "white", size=2)+
geom_vline(xintercept=20, linetype="solid", color = "white", size=2)+
etc

A silly hack, but it works.

Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35