使用Matplotlib的set_xlim和set_ylim后如何显示底部X轴?
解决Matplotlib图表底部X轴不显示的问题
问题原因
你代码里的这两行是关键:
ax.spines['left'].set_position('zero') ax.spines['bottom'].set_position('zero')
ax.spines['bottom'].set_position('zero')会把底部坐标轴(spine)移动到y=0的位置,但如果你的real_values和predicted_values最小值都大于0,再加上你设置的ylim下限是min(...) * 0.95(依然大于0),这条底部spine就会跑到图表可视区域外,自然看不到。
解决方案
根据你的需求选择一种即可:
方案1:不需要坐标轴在原点(最直接)
直接删除设置spine位置的两行代码,让坐标轴回到默认位置:
def plot_experimental_vs_predicted_values(real_values, predicted_values, plot_title, show_plot=True): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(0, len(real_values) + 1) ax.set_ylim(min(chain(predicted_values, real_values)) * 0.95, max(chain(predicted_values, real_values)) * 1.05) # 移除下面两行设置spine位置的代码 # ax.spines['left'].set_position('zero') # ax.spines['bottom'].set_position('zero') ax.plot(range(1, len(real_values) + 1), real_values, '.', label='Experimental value') ax.plot(range(1, len(predicted_values) + 1), predicted_values, '.', label='Estimated value') plt.xlabel('Sample number') plt.ylabel('Experimental or estimated value') plt.legend() plt.title(plot_title) plt.xticks(range(0, len(real_values) + 1)) plt.savefig('Full.png') if show_plot: plt.show() plt.close()
方案2:需要坐标轴在原点(保留十字坐标轴)
调整y轴下限到0,确保y=0在可视范围内,这样底部spine就会显示出来:
def plot_experimental_vs_predicted_values(real_values, predicted_values, plot_title, show_plot=True): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(0, len(real_values) + 1) # 动态设置y轴下限,确保y=0在可视区域内 min_val = min(chain(predicted_values, real_values)) y_min = 0 if min_val > 0 else min_val * 0.95 ax.set_ylim(y_min, max(chain(predicted_values, real_values)) * 1.05) ax.spines['left'].set_position('zero') ax.spines['bottom'].set_position('zero') ax.plot(range(1, len(real_values) + 1), real_values, '.', label='Experimental value') ax.plot(range(1, len(predicted_values) + 1), predicted_values, '.', label='Estimated value') plt.xlabel('Sample number') plt.ylabel('Experimental or estimated value') plt.legend() plt.title(plot_title) plt.xticks(range(0, len(real_values) + 1)) plt.savefig('Full.png') if show_plot: plt.show() plt.close()
内容的提问来源于stack exchange,提问作者Bogdan Doicin
相关产品推荐
相关产品推荐

