[英]How do I squeeze matplotlib bar x-axis labels to drop missing numerical values?
My plotting function produces subplots, in which sometimes it receives regular data to plot by numerical order, and sometimes (case == 'special') the x-labels bars should have different, uniquely ordered numerical values.我的绘图 function 会产生子图,其中有时它会按数字顺序接收到 plot 的常规数据,有时(case == 'special')x-labels 条应该具有不同的、唯一排序的数值。 The problem is that I cannot seem to get rid of the x-axis spaces between the bars.
问题是我似乎无法摆脱条形之间的 x 轴空间。 any idea how to solve?
知道如何解决吗? thanks.
谢谢。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
case = 'special'
data = np.random.rand(10)
if case='regular':
xvec0 = np.linspace(1, len(data), len(data), dtype='uint8')
else:
xvec0 = np.array([3, 4, 5, 9, 10, 11, 12, 13, 18, 20])
fig, axs = plt.subplots(1, 2, figsize=(15, 8))
fig.suptitle('Features Importance Summary', fontsize=16)
med_vec = np.ones(len(xvec0)) * np.median(data)
avg_vec = np.ones(len(xvec0)) * np.mean(data)
axs[0].bar(xvec0, data, edgecolor='k')
axs[0].plot(xvec0, med_vec, 'r--', label='Median')
axs[0].plot(xvec0, avg_vec, 'k--', label='Average')
axs[0].set_xlabel('Feature IDX', size=18)
axs[0].set_ylabel('Normalized feature importance', size=18)
axs[0].xaxis.set_major_locator(mticker.MultipleLocator(1))
axs[0].set_xticks(xvec0)
axs[0].grid(which='major', linestyle=':', linewidth='0.3', color='k')
axs[0].grid(which='minor', linestyle=':', linewidth='0.1', color='k')
axs[0].legend()
fig.show()
Thanks to Mr.T here's a working code in case any one else in the future will encounter the same issue:感谢Mr.T ,这是一个工作代码,以防将来其他人会遇到同样的问题:
fig, axs = plt.subplots(1, 2, figsize=(15, 8))
fig.suptitle('Features Importance Summary', fontsize=16)
med_vec = np.ones(len(xvec0)) * np.median(fi_wl)
avg_vec = np.ones(len(xvec0)) * np.mean(fi_wl)
axs[0].bar(range(len(xvec0)), fi_wl, edgecolor='k')
axs[0].plot(range(len(xvec0)), med_vec, 'r--', label='Median')
axs[0].plot(range(len(xvec0)), avg_vec, 'k--', label='Average')
axs[0].set_xlabel('Feature IDX', size=18)
axs[0].set_ylabel('Normalized feature importance', size=18)
axs[0].xaxis.set_major_locator(mticker.MultipleLocator(1))
axs[0].set_xticks(range(len(xvec0)))
axs[0].set_xticklabels(xvec0)
axs[0].grid(which='major', linestyle=':', linewidth='0.3', color='k')
axs[0].grid(which='minor', linestyle=':', linewidth='0.1', color='k')
axs[0].legend()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.