问题分析
1)问题释义:问题提示的意思就是,指定label格式 即FixedFormatter的时候,需要同时指定这些label的位置/FixedLocator。
2)解决方案:简单来说,用set_ticks
之后就不会出现该提示;但是它会改变原有的tick&label的位置,这是就用到了FixedLocator
。具体展示例子如下:
Answered by Rational-IM
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
x = np.array(range(1000, 5000, 500))
y = 37*x
# 首先,列好图画基础
fig, [ax1, ax2, ax3] = plt.subplots(1, 3, figsize=(12,6))
ax1.plot(x,y, linewidth=5, color='green')
ax2.plot(x,y, linewidth=5, color='red')
ax3.plot(x,y, linewidth=5, color='blue')
# ax1不做任何修改,当一个"control chart"做对比用
# 使用"set_yticks"更新yticks。体现在ax2上
ax2.set_yticks(ax1.get_yticks()) # 和ax1使用一样的个数的yticks。 get_xticks: Return the xaxis' tick locations in data coordinates
# ax1.get_yticks() 结果[ 20000. 40000. 60000. 80000. 100000. 120000. 140000. 160000. 180000.]
ax2.set_yticklabels([f"{x:,.0f}" for x in ax2.get_yticks()])
# 使用matplotlib.ticker.FixedLocator 更新yticks。体现在ax3上
ax3.yaxis.set_major_locator(mticker.FixedLocator(ax1.get_yticks()))
ticks_loc_ax3 = ax3.get_yticks()
ax3.set_yticklabels([f"{x:,.0f}" for x in ticks_loc_ax3])
# 同时搭配使用"MaxNLocator"更新xticks(调整xtick的个数)
ax3.xaxis.set_major_locator(mticker.MaxNLocator(3))
ticks_loc_ax3 = ax3.get_xticks()
ax3.xaxis.set_major_locator(mticker.FixedLocator(ticks_loc_ax3))
ax3.set_xticklabels([f"{x:,.0f}" for x in ticks_loc_ax3])
plt.tight_layout()
plt.show()
对于共x轴的主副坐标轴来说,这样也行:
fig, ax1 = plt.subplots() ax1.plot(<blabla...>, label='label_of_ax1') ax1.set_xticks(<list_of_ax1_xticks>) # 确定xticks的个数 ax1.set_xticklabels(<list_of_ax1_xticks_labels>, rotation=60) # 确定xticks都显示什么labels plt.ylim(min_of_ax1y, max_of_ax1y) plt.legend(loc='upper right') ax2 = ax1.twinx() ax2.plot(<blabla...>, label='label_of_ax2') ax2.set_xticks(<list_of_ax2_xticks>) plt.legend(loc=(0.85, 0.78)) plt.ylim(min_of_ax2y, max_of_ax2y) ax1.grid(axis='x') plt.show()
Axes.set_yticks(ticks, labels=None, *, minor=False, **kwargs)
Set the yaxis’ tick locations and optionally labels.
If necessary, the view limits of the Axis are expanded so that all given ticks are visible.