问题描述
除图形类型外,我对多个图形使用相同的代码。第一个子图的X线是可以的,但是正如您在下图中看到的,即使图形线显示了确切的位置,其他两个子图的X线也缩小了。可能的解决方案是什么?
# Library Loading
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
import pandas as pd
df_1 = pd.DataFrame({
"A":[22.34,25.10,37.57,44.96,53.09],"B":[18.42,31.09,33.66,41.73,51.31],})
df_2 = pd.DataFrame({
"A":[44.85,44.44,44.43,44.06,45.01],"B":[48.46,44.59,43.51,44.42,45.38],})
df_3= pd.DataFrame({
"A":[2.88,6.58,8.35,14.77,20.21],"B":[1.76,5.25,9.18,12.47,19.22],})
plt.figure(num=1)
fig,(ax,ax1,ax2) = plt.subplots(3,1,figsize=(8,12))
# twin_x = ax.twinx() # Create a pseudo axes based off of the original
fig.subplots_adjust(hspace=0.5)
#************** Graph in First row ************************
# Put the bar plot on the "primary y" via ax=ax
df_1[['A','B']]. \
plot(kind='bar',color=['purple','steelblue'],ax=ax,zorder=1,legend=True,width=.40)
ax.grid(True,zorder=0)
ax.set_axisbelow(True)
ax.set_xticklabels(('10','20','30','40','50'),Rotation=360)
# X and Y axis label
ax.set_xlabel('Number of P',fontsize=12)
ax.set_ylabel('(%)',fontsize=12)
#************** Graph in Second row ************************
# Put the bar plot on the "primary y" via ax=ax
df_2[['A','B']]. \
plot(kind='line',ax=ax1,zorder=2,marker='*')
ax1.grid(True,zorder=2)
ax1.set_axisbelow(True)
ax1.set_xticklabels(('10',Rotation=360)
# X and Y axis label
ax1.set_xlabel('Number of P',fontsize=12)
ax1.set_ylabel(' (%)',fontsize=12)
#************** Graph in Third row ************************
# Put the bar plot on the "primary y" via ax=ax
df_3[['A',ax=ax2,zorder=3,marker='o')
ax2.grid(True,zorder=3)
ax2.set_axisbelow(True)
ax2.set_xticklabels(('10',Rotation=360)
# X and Y axis label
ax2.set_xlabel('Number of P',fontsize=12)
ax2.set_ylabel('Time (Seconds)',fontsize=12)
plt.show()
下面是代码中的图像,仅供参考。
解决方法
这是因为后两个图是线图,x轴是数字,matplotlib
将自动缩放xticks
。在这种情况下,后两个图中的xticks
是第一个情节中的[0,0.5,1,...]
与0,2,3,4
。
您可以做的一件简单的事情就是将sharex=True
传递给subplots
:
fig,(ax,ax1,ax2) = plt.subplots(3,figsize=(8,12),sharex=True)
您会得到:
或者您可以手动强制线图的xticks:
# other code
ax2.set_xticks(df_2.index)
ax2.set_xticklabels(('10','20','30','40','50'),Rotation=360)
# same for `ax3`
您会得到: