Skip to main content
 首页 » 编程设计

python之Pandas 散点图 : stop automatic scaling of axis

2024年10月24日10开发

我正在尝试创建两个具有相同轴的独立散点图。正如下面的代码所示,我明确地设置了我的轴限制。但是,由于两个绘图之间的数据分布不同,因此这些限制内的 x 轴缩放 正在发生变化。比较下面的图 1 和图 2,使用相同 代码绘制(不同的 x 值除外):

图一

#set up figure 
fig, ax1 = plt.subplots(1,1) 
 
#plot first series (left y axis) 
df.plot(ax=ax1, kind='line', x=bin1, y='hfall', logx=True, 
        color='DarkBlue', style='.', markersize=5, legend=False) 
 
#set up second axis as duplicate of the first 
ax2 = ax1.twinx() 
 
#plot second series (right y axis) 
df.plot(ax=ax2, kind='line', x=bin1, y='vf', logx=True,  
        color='Red', style='.', markersize=5, legend=False) 
 
#set axes limits 
ax1.set_xlim([0.,0.4]) 
ax1.set_ylim([1,1.15]) 
ax2.set_xlim([0.,0.4]) 
ax2.set_ylim([2e-06,6e-06]) 
 
#set labels and title         
ax1.set_ylabel('Total horizontal flux ($kg/m^2/s$)', color='DarkBlue') 
ax1.set_xlabel('horizontal flux in bin1 ($kg/m^2/s$)') 
ax1.set_title('bin1', loc='center', fontsize=14) 
ax2.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) 
ax2.set_ylabel('Total vertical flux (all bins) ($kg/m^2/s$)', color='Red') 
 
plt.show() 

图2

#set up figure 
fig, ax1 = plt.subplots(1,1) 
 
#plot first series (left y axis) 
df.plot(ax=ax1, kind='line', x=bin2, y='hfall', logx=True, 
        color='DarkBlue', style='.', markersize=5, legend=False) 
 
#set up second axis as duplicate of the first 
ax2 = ax1.twinx() 
 
#plot second series (right y axis) 
df.plot(ax=ax2, kind='line', x=bin2, y='vf', logx=True,  
        color='Red', style='.', markersize=5, legend=False) 
 
#set axes limits 
ax1.set_xlim([0.,0.4]) 
ax1.set_ylim([1,1.15]) 
ax2.set_xlim([0.,0.4]) 
ax2.set_ylim([2e-06,6e-06]) 
 
#set labels and title         
ax1.set_ylabel('Total horizontal flux ($kg/m^2/s$)', color='DarkBlue') 
ax1.set_xlabel('horizontal flux in bin2 ($kg/m^2/s$)') 
ax1.set_title('bin2', loc='center', fontsize=14) 
ax2.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) 
ax2.set_ylabel('Total vertical flux (all bins) ($kg/m^2/s$)', color='Red') 
 
plt.show() 

我很欣赏这可能是为了最好地向我展示我的数据中的可变性,但我想直接比较这些图 - 了解对数刻度上占用空间的变化很有用。那么,有人知道我怎样才能阻止这种 x 轴的自动缩放发生吗? (即我希望两个图上的 x 轴相同)

请您参考如下方法:

您不能在对数轴上将 xlim 设置为 0。尝试将其设置为要匹配的轴低端的数字。例如

ax1.set_xlim([2e-3,0.4]) 
 
ax2.set_xlim([2e-3,0.4])