pandas 条形图中的 y 刻度对齐问题
Issue with y-ticks alignment in pandas bar chart
这是我用来绘制条形图的数据和代码,如输出图中所示。问题在于 y-ticks,我需要让 y-ticks 以垂直方式对齐,以便它们 cover/coincides 所有四个条。如果我们使用 rot = 'some int value' 报价会旋转,但它们不会完全垂直对齐覆盖四个柱。
Polymer
Depth
Residual time
HPAM7030
50
1159
HPAM7030
100
1638
HPAM7030
200
2170
HPAM7030
500
2718
APAM7525
50
2040
APAM7525
100
3101
APAM7525
200
4176
APAM7525
500
5270
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(['science', 'notebook', 'grid'])
df.pivot(index = 'Polymer', columns = 'Depth', values = 'Residual time').plot(kind='barh')
plt.title('Residual time of different polymers (2 year simulation)')
plt.ylabel("Type of Polymer")
plt.xlabel("Residual time (Days)")
plt.show()
我发现使用 pandas 绘图方法返回的 Axes 对象并将 y 刻度标签对齐方式设置为 'center'
:
更容易
ax = df.pivot(index = 'Polymer', columns = 'Depth', values = 'Residual time').plot(kind='barh', rot=90)
ax.set_title('Residual time of different polymers (2 year simulation)')
ax.set(ylabel="Type of Polymer",xlabel="Residual time (Days)")
ax.set_yticklabels(ax.get_yticklabels(), va="center")
这是我用来绘制条形图的数据和代码,如输出图中所示。问题在于 y-ticks,我需要让 y-ticks 以垂直方式对齐,以便它们 cover/coincides 所有四个条。如果我们使用 rot = 'some int value' 报价会旋转,但它们不会完全垂直对齐覆盖四个柱。
Polymer | Depth | Residual time |
---|---|---|
HPAM7030 | 50 | 1159 |
HPAM7030 | 100 | 1638 |
HPAM7030 | 200 | 2170 |
HPAM7030 | 500 | 2718 |
APAM7525 | 50 | 2040 |
APAM7525 | 100 | 3101 |
APAM7525 | 200 | 4176 |
APAM7525 | 500 | 5270 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(['science', 'notebook', 'grid'])
df.pivot(index = 'Polymer', columns = 'Depth', values = 'Residual time').plot(kind='barh')
plt.title('Residual time of different polymers (2 year simulation)')
plt.ylabel("Type of Polymer")
plt.xlabel("Residual time (Days)")
plt.show()
我发现使用 pandas 绘图方法返回的 Axes 对象并将 y 刻度标签对齐方式设置为 'center'
:
ax = df.pivot(index = 'Polymer', columns = 'Depth', values = 'Residual time').plot(kind='barh', rot=90)
ax.set_title('Residual time of different polymers (2 year simulation)')
ax.set(ylabel="Type of Polymer",xlabel="Residual time (Days)")
ax.set_yticklabels(ax.get_yticklabels(), va="center")