简体   繁体   中英

How do I plot a variable number of sets in a python bar chart using matplotlib?

I am trying to write a code that, based on an input dataset, can print a grouped bar chart corresponding to the data set. The dataset can have different scenarios, and each scenario can have different methods. I want to print a group of bars (representing the different methods) for each scenario (see picture below for an example).

条形图示例

The problem is that neither the number of methods nor the number of scenarios are fixed. I cannot figure out how to make my code adapt to different situations. so far my code reads the data set and creates a dictionary where the keys are the different methods, and the values are dictionaries of the scenarios as key and the final value as values.

Example

my_dict = {method1: {scenario1: value1, scenario2: value2, ...}, method2: {scenario1: value1, scenario2: value2, ...}}

I just cannot figure out how to use this dictionary to plot my data. I know that usually I would need to define my categories lists(methods in the example above) but since the number of lists (methods) is variable, I am stuck and don't know how to move from here. Any help will be highly appreciated!

I couldn't figure out how to use my nested dictionary to define the different sets to plot.

import seaborn as sns

my_dict = pd.DataFrame({'method1': {'scenario1': 10, 'scenario2': 20, 'scenario3': 1}, 'method2': {'scenario1': 15, 'scenario2': 5, 'scenario3': 1.5}})

my_dict = my_dict.reset_index()

df = my_dict.melt(id_vars='index')

g = sns.catplot(data=df, x="index", y="value", hue="variable", kind="bar")

This gives me the follow plot:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM