Mike
Mike

Reputation: 25

matplotlib generating multiple figures, 1 blank, 1 wrong, fencepost error?

I'm generating five figures, four line graphs and one scatter plot.

If I generate them separately, they're all fine. If I generate them together, I end up with my first figure blank, figure 2-4 are 'actionable'->'components', and drawn correctly. Figure 5, however has the 'labels' line graphs, with the title and labels from the 'times' scatterplot - and there's no actual scatterplot.

What fencepost or other horror have I wrought?

fn = 0
pltkw = {
    'actionable': {},
    'causes': {},
    'components': {},
    'labels': {},
}

for figure in ['actionable', 'causes', 'components', 'labels']:
    fn += 1
    fig[figure] = plt.figure(fn, figsize=(18,10))
    frm[figure] = pd.DataFrame(data[figure], index=date_range)
    axs[figure] = frm[figure].plot(**pltkw[figure])
    txs[figure] = plt.title(figure)
    yls[figure] = plt.ylabel('events')

fn += 1
figure = 'times'
fig[figure] = plt.figure(fn, figsize=(18,10))
frm[figure] = pd.DataFrame(data[figure])
axs[figure] = plt.scatter(frm[figure]['hour'], frm[figure]['day'])
txs[figure] = plt.title(figure)
xls[figure] = plt.xlabel('hour 0-23')
yls[figure] = plt.ylabel('mon,tue,wed,thu,fri,sat,sun')

plt.show()

Upvotes: 1

Views: 602

Answers (1)

tacaswell
tacaswell

Reputation: 87376

fn = 0
pltkw = {
    'actionable': {},
    'causes': {},
    'components': {},
    'labels': {},
}

for figure in ['actionable', 'causes', 'components', 'labels']:
    # get an axes and figure 
    fig_, ax = plt.subplots(1, 1, figsize=(18, 10)) 
    # I assume you don't _really_ care about the figure numeber, but are using this
    # to get around the global state

    fig[figure] = fig_ 
    axs[figure] = ax
    frm[figure] = pd.DataFrame(data[figure], index=date_range)
    frm[figure].plot(ax=ax, **pltkw[figure])
    # pandas really should return the artists added, but oh well
    txs[figure] = ax.set_title(figure)
    yls[figure] = ax.set_ylabel('events')


figure = 'times'
fig_, ax = plt.subplots(1, 1, figsize=(18, 10))
frm[figure] = pd.DataFrame(data[figure])
axs[figure] = ax
ax.scatter(frm[figure]['hour'], frm[figure]['day'])
txs[figure] = ax.set_title(figure)
xls[figure] = plt.set_xlabel('hour 0-23')
# not sure this is really doing what you want, but ok
yls[figure] = plt.set_ylabel('mon,tue,wed,thu,fri,sat,sun')

plt.show()

Upvotes: 1

Related Questions