当x是字符串时展开x轴(使xlim更宽)

2024-07-07 07:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据框:

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

我想在x轴上绘制Time,在y轴上绘制Minions,在次y轴上绘制Crime_rate问题是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()

代码返回以下绘图: PLOT

我在使用plt.xlim()之前就做过,但是so["Time"]是一个字符串,所以我不能对限制进行减法或加法。如何扩展x轴限制以显示第一个和最后一个条形图?你知道吗


Tags: 数据代码soratetimeplot绘制bar
1条回答
网友
1楼 · 发布于 2024-07-07 07:26:52

我找不到一个解决方案,包括保持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()

FIX

这是因为我从未在ax1中设置x轴,所以它通常被设置为[0, 1, 2, ..., 10, 11]。这样,我可以将x轴的范围设置为从-0.511.5。你知道吗

相关问题 更多 >