I have created a facet
plot as I am not sure how to do this without facet but I am open to alternate ways of doing this.
I have a column with parent category
and another column with sub categories
.
Dummy Data:
import pandas as pd
new_data = {
'date': pd.date_range('2022-01-01', periods=11, freq="ME"),
'parent_category': ['Electronics', 'Electronics', 'Fashion', 'Fashion', 'Home Goods', 'Electronics', 'Fashion','Electronics','Electronics','Electronics','Electronics'],
'child_category': ['Smartphones', 'Laptops', 'Shirts', 'Pants', 'Kitchenware','Laptops', 'Shirts', 'Smartphones','PS4','Oven','Vaccum cleaner']
}
new_data = pd.DataFrame(new_data)
Plot:
import plotnine as p9
from plotnine import *
(ggplot(new_data, aes(x="date", y="child_category", group="child_category")) +
geom_line(size=1, color="pink") +
geom_point(size=3, color="grey") +
facet_wrap("parent_category", ncol=1, scales="free_y") +
theme_538() +
theme(axis_text_x=element_text(angle=45, hjust=1),
panel_grid_major=element_blank(),
figure_size=(8, 6))
)
Issue:
Now when I plot this using facet
it creates facet of same height for each Parent category even when some Parent Categories do not have same number of child Categories. So this creates an unnecessary blank spaces rows in the plot for facets with less child categories.
What I would prefer is and not able to do it: No blank row spacing in facets/ Categorized-sections if the sub categories are less.
Appreciate any help or suggestions:
Example plot shown below: No blank spaces in categories with less subcategories.
from link
One option would be to switch to facet_grid
which using space="free_y"
will set the panel height according to the number of categories. One drawback though is that the strip text will be placed on the right (In R I would use ggforce::facet_col
which allows for a one column layout with space="free_y"
. Unfortunately, TBMK this extension is not available for plotnine
.).
import plotnine as p9
from plotnine import *
(ggplot(new_data, aes(x="date", y="child_category", group="child_category")) +
geom_line(size=1, color="pink") +
geom_point(size=3, color="grey") +
facet_grid("parent_category", scales="free_y", space="free_y") +
theme_538() +
theme(axis_text_x=element_text(angle=45, hjust=1),
panel_grid_major=element_blank(),
strip_text_y=element_text(angle=0), # change facet text angle
figure_size=(8, 6))
)