Aoi Summer
Aoi Summer

Reputation: 35

How to seperate histogram plot into two facet with ggplot in r?

I want to separate my histogram into two parts and zoom the second part. In short, I want to keep the histogram in the original shape, just zoom the x-axis tail. Using mpg dataset as an example, I create a facet label according to 'displ' column and create a histogram plot.

mpg$displn<-scale(mpg$displ)
mpg$myFacet<-"01"
mpg$myFacet[mpg$displn>1]<-"02"
library(ggh4x)
ggplot(mpg,aes(x=displn))+geom_histogram(aes(y=..density..),binwidth = 0.1)+ facet_grid(. ~ myFacet, scales="free", space="free") + scale_x_continuous(breaks = seq(-1.5, 2.5, 1)) + theme(strip.text.x = element_blank())+ theme(panel.spacing=unit(0,'npc')) +force_panelsizes(cols = c(0.3, 1))

The question is the two facets using different 'y=..density..' and looks different from the original figure. Is there any suggestion on how should I improve this? Thanks in advance!

Upvotes: 0

Views: 379

Answers (1)

teunbrand
teunbrand

Reputation: 38053

Typically, one would use ggforce::facet_zoom() for this purpose:

library(ggplot2)
library(ggforce)

ggplot(mpg, aes(x = scale(displ))) +
  geom_histogram(aes(y = after_stat(density)), binwidth = 0.1) +
  facet_zoom(xlim = c(1, 3))

Created on 2022-01-13 by the reprex package (v2.0.1)

The reason your original approach doesn't work is because densities are calculated by group, and data belonging to different panels are automatically separated into different groups.

Upvotes: 2

Related Questions