首页 > 解决方案 > 当 x 是字符串时扩展 x 轴(使 xlim 更宽)

问题描述

我有以下熊猫数据框:

print(so)
       Time  Minions  Crime_rate
0   2018-01     1907    0.147352
1   2018-02     2094    0.165234
2   2018-03     2227    0.148181
3   2018-04     2101    0.135174
4   2018-05     2321    0.132271
5   2018-06     2208    0.128623
6   2018-07     2593    0.140378
7   2018-08     2660    0.145865
8   2018-09     2488    0.149920
9   2018-10     2640    0.152273
10  2018-11     2501    0.138345
11  2018-12     2379    0.134931

我想Time在 x 轴、Minionsy 轴和Crime_rate辅助 y 轴上绘图。问题是 x 轴被裁剪,我想扩展它。我尝试了以下代码:

so.plot(x="Time", y="Minions", kind="bar", color="orange", legend=False)
plt.ylabel("Number of Minions")
so["Crime_rate"].plot(secondary_y=True, rot=90)
plt.ylabel("Minion crime rate")
plt.ylim(0, 1)
# plt.xlim(min, max)
plt.show()

代码返回以下图: 阴谋

我在使用之前已经这样做了plt.xlim(),但是so["Time"]是一个字符串,所以我不能减去或增加限制。如何扩展 x 轴范围以显示第一个和最后一个条形?

标签: pythonmatplotlib

解决方案


我找不到将 x 轴保持为字符串的解决方案。为了解决这个问题,我必须避免设置 x 轴,然后使用set_xticklabels().

fig, ax1 = plt.subplots()
ax1 = so["Minions"].plot(ax=ax1, kind="bar", color="orange", legend=False)
ax2 = ax1.twinx()
so["Crime_rate"].plot(ax=ax2, legend=False)
ax1.set_ylabel("Minions")
ax1.set_xlabel("Time")
ax2.set_ylabel("Minion crime rate")
ax2.set_xlim(-0.5, len(so) - 0.5) # extend the x axis by 0.5 to the left and 0.5 to the right
ax2.set_ylim(0, 1)
ax2.set_xticklabels(so["Time"])
plt.show()

使固定

这是有效的,因为我从未将 x 轴设置为ax1,所以它通常设置为 a [0, 1, 2, ..., 10, 11]。这样,我可以将 x 轴范围设置为-0.511.5


推荐阅读