gpt4 book ai didi

Python - 使用双 x 轴增加 matplotlib 图形大小

转载 作者:行者123 更新时间:2023-12-05 02:19:28 38 4
gpt4 key购买 nike

我有一个使用 matplotlib 的图表,它使用 twinx() 函数显示两个具有不同 y 值的不同图:

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()

我遇到的问题是,当我尝试增加绘图大小时,它会将图表分开。有没有办法增加绘图大小而不分成两个图表?

最佳答案

在任何大小的图形中创建双轴肯定是可能的。只需确保理解自己编写的代码即可。 IE。不要使用 figure 创建新图形,然后提示出现第二个图形。

坚持 matplotlib 状态机接口(interface),解决方案可能如下所示:

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()

或者,如果您更喜欢 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()

关于Python - 使用双 x 轴增加 matplotlib 图形大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42703951/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com