Spurious
Spurious

Reputation: 1995

Subplots mess with my plot

I have the following plot function that saves a random walk input (the random walk is supposed to mimic a stock and bond portfolio that rebalances between each other given specific inputs, the exposure is supposed to show the exposure to the stock portfolio):

def stock_save_img_run(k):
    stock_vals = pd.read_csv('stock_vals_run_' + str(k) + '.csv', sep=';', encoding='utf-8-sig')
    plt.subplot(2, 1, 1)
    plt.plot(stock_vals['date'], stock_vals['stock_val'], color='#191970')
    plt.plot(stock_vals['date'], stock_vals['protected_amt'], color='#191970', ls='dashed')
    plt.stackplot(stock_vals['date'], stock_vals['exposure'] * stock_vals['stock_val'], (1 - stock_vals['exposure']) * stock_vals['stock_val'], color=('gray'), colors=('gray', 'silver'))
    plt.subplot(2, 1, 2)
    plt.plot(stock_vals['date'], stock_vals['exposure'], color='#191970', lw='0.5')
    plt.ylabel('Exposure (in %)')
    plt.savefig('chart_' + str(k) + '.png')
    plt.show()
    plt.cla()
    del stock_vals

The regular output should look like this: correct output

This works for the first run. If I run the script again, the output will look like this: incorrect output

In order to get the plot to look normal again, I have to uncomment this line:
##plt.plot(stock_vals['date'], stock_vals['exposure'], color='#191970', lw='0.5')

As you can imagine, the output will look like this for this particular run: third run to reset

As you can see, the chart on the top looks normal again. When I run it again (fourth run), both charts will look like they are supposed to look. The fifth run will destroy everything again - rinse and repeat.

Given that I know the workaround to get it solved, I'm flabbergasted as to why this occurs.

Upvotes: 0

Views: 2718

Answers (1)

user3822301
user3822301

Reputation:

Obtaining handles over separate Axes instances might be a step in a helpful direction:

def stock_save_img_run(k):
    stock_vals = pd.read_csv('stock_vals_run_' + str(k) + '.csv', sep=';', encoding='utf-8-sig')
    fig, (top_axes, bottom_axes) = plt.subplots(2, 1)
    top_axes.plot(stock_vals['date'], stock_vals['stock_val'], color='#191970')
    top_axes.plot(stock_vals['date'], stock_vals['protected_amt'], color='#191970', ls='dashed')
    top_axes.stackplot(stock_vals['date'], stock_vals['exposure'] * stock_vals['stock_val'], 
                       (1 - stock_vals['exposure']) * stock_vals['stock_val'], color=('gray'),
                       colors=('gray', 'silver'))
    bottom_axes.plot(stock_vals['date'], stock_vals['exposure'], color='#191970', lw='0.5')
    bottom_axes.set_ylabel('Exposure (in %)')
    plt.savefig('chart_' + str(k) + '.png')
    plt.show()
    top_axes.cla()
    bottom_axes.cla()
    del stock_vals

Upvotes: 2

Related Questions