继续在for循环中向图形添加子图

时间:2019-09-03 15:54:37

标签: python pandas matplotlib seaborn

我相信我的问题确实很简单,并且必须有一种非常简单的方法来解决此问题,但是由于我是Python的新手,所以我无法解决它。对于一开始就已经知道子图数量的情况,我看到了多个答案,但是没有一个适用于我的情况。

我正在为一列中的每个唯一值执行foor循环,对于此特定列中的每个唯一值,我将对其两个功能进行散点图绘制。我要寻找的是以下内容:子图的数量将取决于数据帧上某个列的唯一值的数量,该值可能会随我使用脚本加载的文件而有所不同。因此,我想为每个循环在图中添加一个子图。听起来可能令人困惑,但是使用我将在此处发布的代码,事情将变得更加清晰。

这自然是一个比我要尝试的情况更简单的示例:

import pandas as pd
data = {'Column A': [100,200,300,400,500,500,500,300],
'Column B': [1,1,2,2,3,3,0,2], 
'Column C': ["Value_1", "Value_2", "Value_3", "Value_4", "Value_1", 
"Value_2", "Value_3", "Value_4"]}
df = pd.DataFrame(data, columns=['Column A','Column B', 'Column C'])

fig = plt.figure()
for val in df['Column C'].unique():
    sdf = df.loc[df['Column C']==val]
    sdf.plot(x='Column A', y='Column B', label='C = {}'.format(val))

因此,我们的想法是将所有创建的图添加到图形中,图的数量可能因加载的数据而异。

先谢谢了。祝你一切顺利。

1 个答案:

答案 0 :(得分:3)

您可以使用subplots

import pandas as pd
import matplotlib.pyplot as plt

data = {'Column A': [100,200,300,400,500,500,500,300],
'Column B': [1,1,2,2,3,3,0,2], 
'Column C': ["Value_1", "Value_2", "Value_3", "Value_4", "Value_1", 
"Value_2", "Value_3", "Value_4"]}
df = pd.DataFrame(data, columns=['Column A','Column B', 'Column C'])

# The first two argument are the 2 dimension of the matrix of plot
# The figsize param was only to make them bigger in my jupyter notebook

fig, ax = plt.subplots(1, len(df['Column C'].unique()), figsize=(17,5))

for i, val in enumerate(df['Column C'].unique()):
    sdf = df.loc[df['Column C']==val]
    sdf.plot(x='Column A', y='Column B', label='C = {}'.format(val), ax=ax[i])

这是我的结果: enter image description here