Home > Back-end >  Double the amount of subplots when using twinx() in matplotlib
Double the amount of subplots when using twinx() in matplotlib

Time:11-26

Here's my chart:

enter image description here Unfortunately, this is there too, right below:

enter image description here

This is the code:

fig,ax1 = plt.subplots(6,1, figsize=(20,10),dpi=300)
fig2,ax2 = plt.subplots(6,1, figsize=(20,10),dpi=300)

for index, val in enumerate(datedf.columns):
    g = ax1[index].plot(datedf.index, datedf[val], color=colors[index])
    ax1[index].set(ylim=[-100,6500])
    ax2[index] = ax1[index].twinx()
    a = ax2[index].plot(qtydf.index, qtydf[val], color=colors[index], alpha=0.5)
    ax2[index].set(ylim=[200,257000])

I tried this answer but I got an error on the first line (too many values to unpack) Can anyone explain why?

CodePudding user response:

You generate 2 figures, so you end up with 2 figures.

Instead you should do something like:

fig, axes = plt.subplots(6,1, figsize=(20,10),dpi=300)

for index, val in enumerate(datedf.columns):
    ax1 = axes[index]
    g = ax1.plot(datedf.index, datedf[val], color=colors[index])
    ax1.set(ylim=[-100,6500])
    ax2 = ax1.twinx()
    ax2.plot(qtydf.index, qtydf[val], color=colors[index], alpha=0.5)
    ax2.set(ylim=[200,257000])

NB. The code is untested as I don't have the original dataset.

  • Related