Python Matplotlib多个绘图x轴
我在为多重绘图图的X轴添加标签时遇到问题。我目前的代码如下:Python Matplotlib多个绘图x轴,python,matplotlib,Python,Matplotlib,我在为多重绘图图的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) a
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)
我正在将所有X标签轴挤在一起:
您只需设置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()
将为您提供所需的绘图:
您只需设置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()
将为您提供所需的绘图:
我很懒。你能提供实际的数据数组来制作你的图表吗?如果你在
ax1
上设置xticklabels
而不是ax2
,即ax1.setxticklabels(departments)
,会发生什么?我很懒。您能提供实际的数据数组来制作图表吗?如果您在ax1
上设置xticklabels
而不是ax2
,即ax1.设置xticklabels(部门),会发生什么情况
?没问题:)如果答案解决了您的问题,则最好向上投票并接受,以便将问题标记为此处所述已解决-没问题:)如果答案解决了您的问题,则最好向上投票并接受,以便将问题标记为此处所述已解决-