filups21
filups21

Reputation: 1927

plotnine side-by-side histogram with faceting

How can I get a side-by-side histogram that includes faceting? Without faceting, the histogram looks ok, but it's very difficult to compare the counts for groups Two and Three:

from plotnine import *
import pandas as pd 
import numpy as np

quality = ['poor', 'fair', 'good', 'very good', 'excellent']
cat1 = np.random.choice(quality,1000)
cat2 = np.random.choice(quality,1000)
cat3 = np.random.choice(quality,1000)

df = pd.DataFrame({
    'One': pd.Categorical([*cat1, *cat1], categories= quality),
    'group': np.repeat(['Two', 'Three'], len(cat1)),
    'cat': pd.Categorical([*cat2, *cat3], categories= quality)
})

(
    ggplot(df, aes(x = 'cat', fill = 'group'))
    + geom_histogram(bins = 5) # , position = 'dodge'
    + facet_grid('One ~ .')
    + theme(figure_size=(6, 6))
)

enter image description here

But when I add in the position = 'dodge' argument, the bars get very narrow & no longer line up with the x-axis properly:

(
    ggplot(df, aes(x = 'cat', fill = 'group'))
    + geom_histogram(bins = 5, position = 'dodge')
    + facet_grid('One ~ .')
    + theme(figure_size=(6, 6))
)

enter image description here

The same thing happens with position = position_dodge(.75) instead of position = 'dodge' (not shown).

Upvotes: 2

Views: 635

Answers (1)

has2k1
has2k1

Reputation: 2375

Since the x aesthetic is discrete, you should use geom_bar.

(
    ggplot(df, aes(x = 'cat', fill='group'))
    + geom_bar(position='dodge', width=.95)
    + facet_grid('One ~ .')
    + theme(figure_size=(6, 6))
)

enter image description here

Upvotes: 2

Related Questions