﻿ Use a Loop to Plot N Charts Python - ITCodar

# Use a Loop to Plot N Charts Python

## Use a loop to plot n charts Python

Ok, so the easiest method to create several plots is this:

``import matplotlib.pyplot as pltx=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]for i in range(len(x)):    plt.figure()    plt.plot(x[i],y[i])    # Show/save figure as desired.    plt.show()# Can show all four figures at once by calling plt.show() here, outside the loop.#plt.show()``

Note that you need to create a `figure` every time or `pyplot` will plot in the first one created.

If you want to create several data series all you need to do is:

``import matplotlib.pyplot as pltplt.figure()x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')``

You could automate it by having a list of colours like `['r','g','b','k']` and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):

``import matplotlib.pyplot as pltx=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]colours=['r','g','b','k']plt.figure() # In this example, all the plots will be in one figure.    for i in range(len(x)):    plt.plot(x[i],y[i],colours[i])plt.show()``

17 Dec 2019: added `plt.show()` and `plt.figure()` calls to clarify this part of the story.

## How to plot charts side by side with a forloop

Here i have used the plot function of dataframe, Also i like plotting in different colors so i do this small trick.

``#CODEimport pandas as pdfrom pandas import datetimefrom pandas import DataFrame as dfimport matplotlibfrom pandas_datareader import data as webimport matplotlib.pyplot as pltimport datetimeimport numpy as npcolors = ["b",'g','r','c','m','y','k']stocks = 'GE','F' #<-- In this case there are just 2 symbols but this could be more start = datetime.date(2000,1,1)end = datetime.date.today()data = web.DataReader(stocks, 'yahoo',start, end)# THIS MAKES A GRID OF 1 ROW and len(stocks) COLUMN and figure size as (width, height) in inches.fig, axs = plt.subplots(1, len(stocks), figsize=(30, 5))i = 0#iterate for each stockfor stock in stocks:    # i'th close stock will plot on i'th axs (Note: Whatever be your grid)    data["Close"][stock].plot(ax=axs[i],color=colors[i%len(colors)])    i += 1#show plotplt.show()``

## Creating multiple plots with for loop?

By default, seaborn.barplot() plots data on the current Axes. If you didn't specify the Axes to plot on, the latter will override the previous one. To overcome this, you can either create a new figure in each loop or plot on a different axis by specifying the `ax` argument.

``import matplotlib.pyplot as pltfor df in dfs:    data = dfs[df].head(n=10)    plt.figure() # Create a new figure, current axes also changes.    sns.barplot(data=data, x='x_col', y='y_col', color='indigo').set_title(df) ``

## Plotting multiple figures in a loop

Try the following:

``import matplotlib.pyplot as pltimport numpy as npx = np.arange(0,10)y = np.arange(0,10)for _ in range(2):   plt.figure() # add this statement before your plot   plt.plot(x,y)   plt.show()``

## For loop for plotting multiple plots in matplotlib

Just put `plt.show()` in your routine:

``for symbol in symbols:    data = con.get_candles(symbol, period='D1', start = start, end = end)    data1 = con.get_candles('USOil', period='D1', start = start1, end = end)    ax = data['bidclose'].plot()    data1['bidclose'].plot(ax=ax)    plt.show()``