Home > Back-end >  How to plot a boxplot from a nested dictionary
How to plot a boxplot from a nested dictionary

Time:04-05

I have a nested dictionary, a subset of which is given below:

dict_a = {
    '2019': {
        'Jan-Mar': {
            'category_A': [0.0, 11.344454217292942, 4.885790495524913], 
            'category_B': [0.0, 14.657371486574736, 0.0, 4.885790495524913]
            },
        'Apr-June': {
            'category_A': [4.885790495524913, 0.0, 7.7437947217868235, 7.7437947217868235],
            'category_B': [7.7437947217868235, 0.0, 0.0, 0.0]
            }
            },
    '2020': {
        'Jan-Mar': {
            'category_A': [7.7437947217868235, 7.7437947217868235, 21.787848617781385],
            'category_B': [4.885790495524913, 4.885790495524913, 0.0, 7.7437947217868235]
            },
        'Apr-June': {
            'category_A': [0.0, 11.344454217292942, 0.0, 7.7437947217868235], 
            'category_B': [4.885790495524913, 0.0, 4.885790495524913]
            }
            }
}

I am trying to plot a boxplot of the data for a given category, such that the x axis is the month group (e.g. 'Jan-Mar') and the legend shows the year (e.g. '2019') for each box. For instance, for category_A, I would have two boxplots per month group, each corresponding to a given year, with a legend displaying the year for each box.

I have tried converting the dictionary to a pandas dataframe but have struggled with multiindex plotting. I would like to know if there is a far simpler method using the original dictionary. Any help appreciated. Thank you.

CodePudding user response:

For boxplots with many dimensions, seaborn's sns.catplot is handy. Seaborn prefers its data as a dataframe in sns.catplot from nested dictionary

Seaborn lets you easily experiment exchanging the roles of x=, hue=, col= and/or row=. It also lets you try out different kinds of plots (e.g. kind='violin').

  • Related