Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate multiple plots with for loop; display output in matplotlib subplots

Objective: To generate 100 barplots using a for loop, and display the output as a subplot image

Data format: Datafile with 101 columns. The last column is the X variable; the remaining 100 columns are the Y variables, against which x is plotted.

Desired output: Barplots in 5 x 20 subplot array, as in this example image: Subplot - 3 x 2 array example

Current approach: I've been using PairGrid in seaborn, which generates an n x 1 array: example output.

where input == dataframe; input3 == list from which column headers are called:

for i in input3:
    plt.figure(i)
    g = sns.PairGrid(input,
             x_vars=["key_variable"],
             y_vars=i,
             aspect=.75, size=3.5)
    g.map(sns.barplot, palette="pastel")

Does anyone have any ideas how to solve this?

like image 817
LSL Avatar asked Oct 18 '22 09:10

LSL


1 Answers

To give an example of how to plot 100 dataframe columns over a grid of 20 x 5 subplots:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

data = np.random.rand(3,101)
data[:,0] = np.arange(2,7,2)
df = pd.DataFrame(data)

fig, axes = plt.subplots(nrows=5, ncols=20, figsize=(21,9), sharex=True, sharey=True)
for i, ax in enumerate(axes.flatten()):
    ax.bar(df.iloc[:,0], df.iloc[:,i+1])
    ax.set_xticks(df.iloc[:,0])

plt.show()

enter image description here

like image 189
ImportanceOfBeingErnest Avatar answered Oct 21 '22 03:10

ImportanceOfBeingErnest