简体   繁体   中英

How do I plot a line graph for each row using matplotlib subplots?

I am trying to plot a bond yield curve (line graph) for every row of my data using subplots. How do I go about using loops to create that? Is it possible to have a 5 by 20 plot (100 subplots in total)?

This is the dataframe I am working on. I've looked at other post and came up with the code below. https://imgur.com/HbsqI8i

df = pd.read_csv("treasury_yields.csv")

fig, ax = plt.subplots(nrows=20, ncols=5)

for row in ax:
    for col in row:
        col.plot(x, y)

plt.show()

https://imgur.com/djX5dQS

I am hoping to generate something similar to the diagram above. I am still new and I am not exactly sure where to begin.

You could do something like:

Given this data:

            1 mo  2 mo   3 mo   6 mo  1 yr  2 yr  3 yr  5 yr  7 yr  10 yr  \
30/11/2018  2.31   2.33   2.37  2.52  2.70  2.80  2.83  2.84  2.92   3.01   
31/12/2018  2.44   2.45   2.45  2.56  2.63  2.48  2.46  2.51  2.59   2.69   
31/01/2019  2.42   2.43   2.41  2.46  2.55  2.45  2.43  2.43  2.51   2.63   
28/02/2019  2.44   2.47   2.45  2.50  2.54  2.52  2.50  2.52  2.63   2.73   
31/03/2019  2.43   2.44   2.40  2.44  2.40  2.27  2.21  2.23  2.31   2.41   
30/04/2019  2.43   2.44   2.43  2.46  2.39  2.27  2.24  2.28  2.39   2.51   
31/05/2019  2.35   2.38   2.35  2.35  2.21  1.95  1.90  1.93  2.03   2.14   
30/06/2019  2.18   2.15   2.12  2.09  1.92  1.75  1.71  1.76  1.87   2.00   
31/07/2019  2.01   2.07   2.08  2.10  2.00  1.89  1.84  1.84  1.92   2.02   
31/08/2019  2.10   2.04   1.99  1.89  1.76  1.50  1.42  1.39  1.45   1.50   
            20 yr  30 yr  
30/11/2018   3.19   3.30  
31/12/2018   2.87   3.02  
31/01/2019   2.83   2.99  
28/02/2019   2.94   3.09  
31/03/2019   2.63   2.81  
30/04/2019   2.75   2.93  
31/05/2019   2.39   2.58  
30/06/2019   2.31   2.52  
31/07/2019   2.31   2.53  
31/08/2019   1.78   1.96  

Code:

fig, axes = plt.subplots(nrows=2, ncols=5, figsize=(16, 8))

for row, ax in zip(df.index, axes.flatten()):
    ax.plot(df.loc[row].values)
    ax.set_title(row, fontsize=10)
    ax.set_xticks(range(df.shape[1]))
    ax.set_xticklabels(list(df.columns), rotation=90, fontsize=8)
plt.show()

Result: 在此处输入图片说明

You might want to tidy it up a bit, and extend it for your (20, 5) dimensions.

Also see this tutorial, looks similar to what you want: https://napsterinblue.github.io/notes/python/viz/subplots/

Except in that case they're plotting columns, not rows.

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv("treasury_yields.csv")

fig, ax = plt.subplots(nrows=20, ncols=5)

for row in range(20):
    for col in range(5):
        ax[row,col].plot(x, y)

plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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