简体   繁体   English

Matplotlib多图x轴

[英]Matplotlib multiple plots x axis

I am having a problem with labelling the X-axis of a multiple plot graph. 我在标注多个绘图图的X轴时遇到问题。 My current code is as follows: 我当前的代码如下:

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)

I am getting all the X-label axis crammed together: 我将所有X标签轴都塞满了: 在此处输入图片说明

You simply need to set to position of your x ticks as well as setting the label using: 您只需要设置x刻度的位置以及使用以下方法设置标签即可:

ax2.set_xticks(X)

otherwise matplotlib will try and put your labels onto the ticks it generates automatically. 否则,matplotlib会尝试将您的标签放在它自动生成的刻度上。

A full example with some fake data: 带有一些伪造数据的完整示例:

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()

Will give you the required plot: 将为您提供所需的绘图:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM