meepl meepl - 1 year ago 76
Python Question

Matplotlib subplots where one graph has multiple lines with and one doesn't

currently trying this:

fig, ax1, ax3 = plt.subplots(1, 2, figsize=(10,5))

# share rate line and ax
ax1.plot(temp_df.index, temp_df['share_rate'], 'b-')

# % of total video views line and ax
ax2 = ax1.twinx()
ax2.plot(temp_df.index, temp_df['percent_of_total_views'], 'r-')

# third plot
ax3.plot([1,2,3,4], [1,2,3,4])

but receiving this error:

ValueError Traceback (most recent call last)
<ipython-input-62-a8364e1f65f8> in <module>()
10 print "average share rate: "
---> 12 fig, ax1, ax3 = plt.subplots(1, 2, figsize=(10,5))
14 # share rate line and ax

ValueError: need more than 2 values to unpack

Answer Source

You are using matplotlibs subplots-function in a wrong way.

The statement of yours

fig, ax1, ax3 = plt.subplots(1, 2, figsize=(10,5))  # WRONG 3 vars on left, 2 are returned

expects a tuple of size 3 returned, which are put into fig, ax1, ax3.

But the function returns only a tuple of size 2, fig, ax where ax can be a single axis, or a sequence of axis-objects (see docs).

If you know, that this ax is a sequence of size 2, you could unpack it directly on the left side with:

fig, (ax1, ax3) = plt.subplots(1, 2, figsize=(10,5))  # CORRECT because 2nd return-value unpacked
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download