我在标记多图表图的X轴时遇到问题。我目前的代码如下:
X=range(0, len(departments), 1)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.bar(X, department_employees_current, color='b')
ax1.bar(X, department_employees_left, color='r', bottom=department_employees_current)
ax1.set_ylabel('Employees current & left')
ax2 = ax1.twinx()
ax2.plot(X, department_percentage_attrition, color='r')
ax2.set_ylabel('% Attrition')
ax2.set_xticklabels(departments)
答案 0 :(得分:3)
您只需设置x刻度的位置以及使用以下设置标签:
ax2.set_xticks(X)
否则matplotlib会尝试将标签放在它自动生成的刻度线上。
包含一些虚假数据的完整示例:
departments = ["Test1","Test2","Test3"]
department_employees_current = [80,800,300]
department_employees_left = [20,100,80]
department_percentage_attrition = [700,50,900]
X=range(0, len(departments), 1)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.bar(X, department_employees_current, color='b')
ax1.bar(X, department_employees_left, color='r', bottom=department_employees_current)
ax1.set_ylabel('Employees current & left')
ax2 = ax1.twinx()
ax2.plot(X, department_percentage_attrition, color='r')
ax2.set_ylabel('% Attrition')
ax2.set_xticks(X)
ax2.set_xticklabels(departments)
plt.show()
会给你所需的情节: