Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Space between my geom_histogram bars-not barplot

Tags:

r

ggplot2

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

like image 812
Marvin Schopf Avatar asked Jul 03 '17 15:07

Marvin Schopf


4 Answers

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.

like image 57
KoenV Avatar answered Oct 08 '22 16:10

KoenV


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

like image 39
Tamas Nagy Avatar answered Oct 08 '22 17:10

Tamas Nagy


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

like image 31
Ghazal Avatar answered Oct 08 '22 18:10

Ghazal


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..))
like image 2
Amadou Kone Avatar answered Oct 08 '22 18:10

Amadou Kone