[英]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:这给了我以下情节:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.