简体   繁体   中英

Adding to a subplot figure using a for loop

My question is pretty simple. I have this function that creates a certain graph for each column in a dataframe. The output however is 7 separate graphs. I am able to make a 4x2 subplot like this:

f, axarr = plt.subplots(4, 2, figsize = (10, 10))

to get this empty chart

here is the code for my plots. How can/should I make it fill in the subplot instead of returning 7 separate plots? including the head of the data frames for reference

for index in weights.columns:    
    fig = plt.figure(figsize = (10, 6))
    ax = fig.add_subplot(1, 1, 1)
    ##this gets the bottom axis to be in the middle so you can see 
    ##clearly positive or negative returns
    ax.spines['left'].set_position(('data', 0.0))
    ax.spines['bottom'].set_position(('data', 0.0))

    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')

    ax.set_ylabel('{} One month forward return'.format(index))
    ax.set_xlabel('Percent of Max Exposure')

    ##get the ticks in percentage format

    ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:.0%}'.format(y)))
    ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: '{:.0%}'.format(x)))

    plt.title('One Month Forward {} Returns Versus Total Exposure'.format(index))
    plt.scatter(weights_scaled[index], forward_returns[index], marker = 'o')

weights_scaled.head()

Out[415]: US Equities Dev Ex-US BMI Emerging BMI US Real Estate
Date
1999-12-31 0.926819 0.882021 0.298016 0.0
2000-01-31 0.463410 0.882021 0.298016 1.0
2000-02-29 0.463410 0.882021 0.298016 0.5
2000-03-31 0.926819 0.882021 0.298016 1.0
2000-04-28 0.926819 0.441010 0.000000 1.0

        Commodity  Gold  US Bonds  

Date
1999-12-31 1.0 1.0 0.051282
2000-01-31 1.0 1.0 0.232785
2000-02-29 1.0 1.0 0.258426
2000-03-31 1.0 0.5 0.025641
2000-04-28 1.0 0.5 0.244795

This piece of code is causing the issue:

for index in weights.columns:    
    fig = plt.figure(figsize = (10, 6))
    ax = fig.add_subplot(1, 1, 1)

For every column it is creating a new figure and a new axis on that figure. Instead you should return to your first instinct with the axarr and then when you iterate the columns in your dataframe, assign one of the axes of that array to a variable on which to plot the data in that column.

One dummy example looks like this:

# Create array of 8 subplots
f, axarr = plt.subplots(4, 2, figsize=(10,10))

# Create dummy data for my example
new_dict = {c: np.random.randint(low=1, high=10, size=40) for c in ['a','b','c','d','e','f','g']}

df = pd.DataFrame(new_dict)

# Enumerate columns, providing index and column name
for i, col in enumerate(df.columns):

    # Select subplot from list generated earlier
    ax = axarr.flat[i]

    # Select column and plot data on subplot axis
    df[col].hist(ax=ax)

子图

Editing the relevant parts of your code, I think you want:

for i, col in enumerate(weights.columns):    

    ax = axarr.flat[i]

    ax.set_ylabel('{} One month forward return'.format(col))

    ...

    plt.title('One Month Forward {} Returns Versus Total Exposure'.format(col))
    plt.scatter(weights_scaled[col], forward_returns[col], marker = 'o')

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