简体   繁体   English

使用 pandas.plot() 在子图中堆叠条形图 plot

[英]Stacked bar plot in subplots using pandas .plot()

I created a hypothetical DataFrame containing 3 measurements for 20 experiments.我创建了一个假设的 DataFrame,其中包含 20 个实验的 3 个测量值。 Each experiment is associated with a Subject (3 possibilities).每个实验都与一个主题(3 种可能性)相关联。

import random
    
random.seed(42) #set seed
tuples = list(zip(*[list(range(20)),random.choices(['Jean','Marc','Paul'], k = 20)]))#index labels
index=pd.MultiIndex.from_tuples(tuples, names=['num_exp','Subject'])#index
test= pd.DataFrame(np.random.randint(0,100,size=(20, 3)),index=index,columns=['var1','var2','var3']) #DataFrame
test.head() #first lines

head

I succeeded in constructing stacked bar plots with the 3 measurements (each bar is an experiment) for each subject:我成功地为每个主题构建了带有 3 个测量值的堆叠条形图(每个条形都是一个实验):

test.groupby('Subject').plot(kind='bar', stacked=True,legend=False) #plots

plot1 plot2 plot3情节1 情节 2情节 3

Now, I would like to put each plot (for each subject) in a subplot.现在,我想将每个 plot(对于每个主题)放在一个子图中。 If I use the "subplots" argument, it gives me the following:如果我使用“subplots”参数,它会给我以下信息:

test.groupby('Subject').plot(kind='bar', stacked=True,legend=False,subplots= True) #plot with subplot

plotsubplot1 plotsubplot2 plotsubplot3 plotsubplot1 plotsubplot2 plotsubplot3

It created a subplot for each measurment because they correspond to columns in my DataFrame. I don't know how I could do otherwise because I need them as columns to create stacked bars.它为每个测量创建了一个子图,因为它们对应于我的 DataFrame 中的列。我不知道我还能怎么做,因为我需要它们作为列来创建堆叠条。

So here is my question: Is it possible to construct this kind of figure with stacked bar plots in subplots (ideally in an elegant way, without iterating)?所以这是我的问题:是否有可能在子图中使用堆叠条形图构建这种图形(理想情况下以优雅的方式,无需迭代)?

Thanks in advance !提前致谢 !

I solved my problem with a simple loop without using anything else than pandas.plot()我用一个简单的循环解决了我的问题,除了 pandas.plot()

Pandas.plot() has an ax parameters for matplotlib axes object. Pandas.plot() 有一个轴参数 matplotlib 轴 object。

So, starting from the list of distinct subjects:因此,从不同主题的列表开始:

subj= list(dict.fromkeys(test.index.get_level_values('Subject')))

I define my subplots:我定义我的子图:

fig, axs = plt.subplots(1, len(subj))

Then, I have to iterate for each subplot:然后,我必须对每个子图进行迭代:

 for a in range(len(subj)):
    test.loc[test.index.get_level_values('Subject') == subj[a]].unstack(level=1).plot(ax= axs[a], kind='bar', stacked=True,legend=False,xlabel='',fontsize=10) #Plot
    axs[a].set_title(subj[a],pad=0,fontsize=15) #title 
    axs[a].tick_params(axis='y', pad=0,size=1) #yticks

And it works well: : finalresult它运作良好::最终结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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