Adding Space between my geom_histogram bars-not barplot

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


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.


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

Tags:

R

Ggplot2