Jeff Saltfist
Jeff Saltfist

Reputation: 943

Python - increase matplotlib figure size with dual x axis

I have a chart using matplotlib that uses the twinx() function to display two different plots with different y values:

plt.plot(Current_Time[1000:66000],Avg_Duration[1000:66000],color='blue',label="Average Duration of All Parked Cars")
#plt.figure(figsize=(10,10))
plt.legend(loc='upper left')
plt.ylim(0,50000)
plt.ylabel('Duration in Seconds')
plt.xticks(rotation=90)
plt2=plt.twinx()
#plt2.figure(figsize=(10,10))
plt2.plot(Current_Time[1000:66000],Quantity[1000:66000],color='purple',label='Quantity of Cars Parked')
plt2.set_ylabel('Cars Parked')
plt2.legend(loc='upper right')
plt.show()

The issue I am having is when I try to increase the plot size, it separates the charts. Is there a way to increase the plot size and not split into two charts?

Upvotes: 3

Views: 4797

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

It's sure possible to create twin axes in a figure of any size. One just has to make sure to understand the code one's writing. I.e. don't create a new figure using figure and then complain that there is a second figure appearing.

Sticking to the matplotlib state machine interface, a solution could look like this:

import matplotlib.pyplot as plt
import numpy as np

#get data
x=np.arange(40)
y=np.random.rand(len(x))*20000+30000
y2=np.random.rand(len(x))*0.5
#create a figure
plt.figure(figsize=(10,10))
#plot to first axes
plt.plot(x,y,color='blue',label="label1")
plt.ylim(0,50000)
plt.ylabel('ylabel1')
plt.xticks(rotation=90)
#create twin axes
ax2=plt.gca().twinx()
#plot to twin axes
plt.plot(x,y2,color='purple',label='label2')
plt.ylabel('ylabel2')
plt.legend(loc='upper right')
plt.show()

Or, if you prefer the matplotlib API:

import matplotlib.pyplot as plt
import numpy as np

#get data
x=np.arange(40)
y=np.random.rand(len(x))*20000+30000
y2=np.random.rand(len(x))*0.5
#create a figure
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
#plot to first axes
ax.plot(x,y,color='blue',label="label1")
ax.set_ylim(0,50000)
ax.set_ylabel('ylabel1')
ax.set_xticklabels(ax.get_xticklabels(),rotation=90)
#create twin axes
ax2=ax.twinx()
#plot to twin axes
ax2.plot(x,y2,color='purple',label='label2')
ax2.set_ylabel('ylabel2')

h1, l1 = ax.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax.legend(handles=h1+h2, labels=l1+l2, loc='upper right')
plt.show()

Upvotes: 5

Related Questions