【问题标题】:Python Way to Create Multiple Plots in a Loop?在循环中创建多个绘图的 Python 方法?
【发布时间】:2020-07-23 14:54:03
【问题描述】:

创建多个绘图的 Python 方法是什么?

我在下面编写了一些带有绘图变量的代码。我的直觉是编写一组对象进行迭代。看起来 Python 中的对象比我习惯的那种 Javascript/JSON 对象要复杂一些。

关于“Python 方式”的任何提示来完成我需要在这里完成的事情?

import pandas as pd
            
import networkx as nx 
from networkx.algorithms 
import community
import matplotlib.pyplot as plt
from datetime import datetime
         

graph = pd.read_csv('C:/Users/MYDIR/MYSOURCE.csv')
filename_prefix = datetime.now().strftime("%Y%m%d-%H%M%S")

#begin stuff that changes every plot
filename_suffix = 'suffix_one'
directory = 'C:/Users/MYDIR/';
    
title='MY_TITLE'
    
axis1='AXIS1';
    
axis2='AXIS2';
    
color = 'lightgreen';
#end stuff that changes every plot

df = graph[[axis1,axis2]]
G = nx.from_pandas_edgelist(df, axis1, axis2 );
plt.figure(figsize=(10,5))
    
ax = plt.gca()
ax.set_title(title)
nx.draw(G,with_labels=True, node_color=color, ax=ax)
_ = ax.axis('off')

#plt.show()
    
plt.savefig(directory + filename_prefix +'_' + title);
#plt.savefig(filename_prefix +'_' + filename_suffix + '.png')

【问题讨论】:

标签: python matplotlib networkx


【解决方案1】:

数组是python中的列表,它们是可迭代的。如果您打算使用这些对象的列表,您可以遍历每个元素并保存结果图?您想对每个情节做一些特别的事情吗?

【讨论】:

  • 我想对每个数据集执行完全相同的操作。在其他语言中,我会将绘图参数放在一个数组中,并将绘图创建代码放在一个循环中。
  • 是的,你可以在 python 中做同样的事情,循环遍历列表或字典!
【解决方案2】:

我修改了来自 these kind folks 的代码,以创建接近我认为可行的东西:

import numpy as np
    
import matplotlib.pyplot as plt

x = np.linspace(0, 5, 10)
y = x * x

#fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True)

titles = ['Linear', 'Squared', 'Cubic', 'Quartic']
y_vals = [x, x * x, x**3, x**4]

# axes.flat returns the set of axes as a flat (1D) array instead
    
# of the two-dimensional version we used earlier
    

for title, y in zip(titles, y_vals):
        
    fig, ax = plt.subplots()
        
    ax.plot(x, y)
        
    ax.set_title(title)
        
    ax.grid(True)
        
    plt.savefig('C:/MyData/' +title + '_.png')
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-16
    • 2020-01-14
    • 2021-01-10
    • 1970-01-01
    • 2014-07-24
    • 2015-10-23
    • 1970-01-01
    相关资源
    最近更新 更多