SiH
SiH

Reputation: 1546

draw only outline of multiple histograms in ggplot to clearly visualize

Below is code to generate two histograms. But due to significant overlap, it is difficult to see each distibution clearly.

How can I can only plot a thicker outline of each histogram and remove the vertical lines/bars.

enter image description here

Desirable histogram should look this -

enter image description here

library(tidyverse)

A <- rnorm(n = 1000, mean = 0, sd = 1)
B <- rnorm(n = 1000, mean = 0.1, sd = 1.3)

tbl <- tibble(A, B) %>%
  # pivot longer
  pivot_longer(cols = everything(),
               names_to = "Distributions",
               values_to = "values")

ggplot(data = tbl,
       aes(x = values,
           col = Distributions,
           fill = Distributions)) + 
  geom_histogram(bins = 50,
                 alpha = 0.3,
                 position = "identity") + 
  theme_bw()

Upvotes: 2

Views: 417

Answers (1)

teunbrand
teunbrand

Reputation: 38003

You can combine a borderless histogram with a geom_step() layer for the outline.

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.1
#> Warning: package 'readr' was built under R version 4.1.1

A <- rnorm(n = 1000, mean = 0, sd = 1)
B <- rnorm(n = 1000, mean = 0.1, sd = 1.3)

tbl <- tibble(A, B) %>%
  # pivot longer
  pivot_longer(cols = everything(),
               names_to = "Distributions",
               values_to = "values")

ggplot(data = tbl,
       aes(x = values,
           col = Distributions,
           fill = Distributions)) + 
  geom_step(
    stat = "bin", bins = 50,
    direction = "mid"
  ) +
  geom_histogram(
    bins = 50, alpha = 0.3, colour = NA,
    position = "identity"
  )

Created on 2021-09-24 by the reprex package (v2.0.1)

Upvotes: 7

Related Questions