简体   繁体   English

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

[英]Keep adding subplots to a figure in a for loop

I believe that my problem is really straightforward and there must be a really easy way to solve this issue, however as I am quite new with Python, I could not sort it out. 我相信我的问题确实很简单,并且必须有一种非常简单的方法来解决此问题,但是由于我对Python相当陌生,所以无法解决。 I saw multiple answer for cases in which the number of subplots is already known at first, but none apply to my case. 对于最初已经知道子图数量的情况,我看到了多个答案,但没有一个适用于我的情况。

I am doing a foor loop for each unique value in a column, and for every unique value in this specific column, I will make a scatter plot of two of it's features. 我正在为列中的每个唯一值执行foor循环,并且针对此特定列中的每个唯一值,我将对其两个功能进行散点图绘制。 What I am looking for is the following: The number of subplot will depend on the number of unique values of a certain column on my dataframe, which may vary depending on which file I load with the script. 我要寻找的是以下内容:子图的数量将取决于数据帧上某个列的唯一值的数量,该值可能会随我使用脚本加载的文件而有所不同。 Hence, I want for each loop, add a subplot to the figure. 因此,我想为每个循环在图中添加一个子图。 May sound confusing, but with the code that I will post here things will get clearer. 听起来可能令人困惑,但是使用我将在此处发布的代码,情况将变得更加清晰。

This is naturally a way simpler example than the case in which I am trying to work on: 与我正在尝试的情况相比,这自然是一个更简单的示例:

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))

So, the idea is to add all the created plots, whose quantity may vary depending on the loaded data, to the figure. 因此,该想法是将所有创建的图(其数量可能随加载的数据而变化)添加到图中。

Thanks in advance. 提前致谢。 Wish you the best. 祝你好运。

You can use subplots . 您可以使用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])

And this was my result: 这就是我的结果: 在此处输入图片说明

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

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