0

What is the Python way to create multiple plots?

I've written some code below with plotting variables. My instinct is to write an array of objects to iterate through. It seems like objects in Python are a little more complex than the sort of Javascript/JSON objects I've gotten used to.

Any tips on the 'Python Way' to accomplish what I need to here?

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')
  • Multiple subplots of what exactly? You only seem to have one graph in this example. Though here's an example for the general case https://stackoverflow.com/questions/61040515/plot-multiple-histograms-as-a-grid/61040745#61040745 – yatu Jul 23 '20 at 15:18

2 Answers2

1

Arrays are lists in python, they iterable. If you plan to use a list of these objects, you can iterate through each element and save the resulting plots? Are you wishing to do something special with each plot?

  • I want to do the exact same operations to each data set. In other languages I would put the plot parameters in an array and put the plot creation code in a loop. – Matthew David Jankowski Jul 24 '20 at 13:28
  • Yep you can do the same in python, loop through a list or dictionaryy! –  Jul 24 '20 at 19:38
0

I adapted the code from these kind folks to create something close to what I decided would work:

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