在Matplotlib中隐藏x轴标签

时间:2019-12-30 07:29:00

标签: python-3.x matplotlib

我已使用条形图显示以下数据框:

   city   pred  actual
9     j  10.05   12.68
0     a   9.72    9.56
6     g   8.29    9.11
2     c   8.22    8.49
3     d   7.88    7.92
8     i   7.04    7.35
5     f   6.06    6.33
1     b   5.94    6.00
7     h   5.52    5.72
4     e   5.37    5.62
10    k   6.04    5.50

要绘制的代码:

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = (10, 7)

colors = ['b', 'g', 'r', 'c', 'm', 'y', 'g']
df = df.sort_values(by=['actual'], ascending=False)
ax = df.plot(x="city", y=["actual", "pred"], kind="bar", color = colors, alpha=0.8)
plt.legend(["actual", "pred"], fontsize=15)
plt.gca().set_xticklabels(df['city'])
plt.suptitle("pred vs actual", fontsize=18)
for p in ax.patches:
    ax.annotate(np.round(p.get_height(),decimals=2), (p.get_x()+p.get_width()/2., \
                         p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')
plt.tight_layout()
plt.show()

输出: enter image description here 我正在尝试做的是从x轴隐藏不需要的 city 文本标签。我的预期输出将是这样的:

enter image description here

我该怎么做?谢谢。

1 个答案:

答案 0 :(得分:0)

这行代码是我发现的唯一代码:

ax.xaxis.label.set_visible(False)

如果您还有其他解决方案,欢迎分享。

相关问题