python - 当 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 轴、Minions
y 轴和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 轴范围以显示第一个和最后一个条形?
解决方案
我找不到将 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.5
至11.5
。
推荐阅读
- android - 如何通过改造将数组嵌套对象 Json 解析为 Kotlin?
- node.js - 在 MERN 堆栈应用程序的身份验证过程中结合电话号码验证的最佳方法
- c# - ASP.NET Core:使用动作过滤器向方法添加自定义参数
- django - Wagtail 流图像忽略 HTML 文件
- windows - 什么 Windows SDK 用于监视用户活动?
- node.js - 尝试将我的 API 部署到 heroku 时遇到此问题
- javascript - 在此 AJAX 调用循环上设置延迟
- python - 用作索引的 Python 数组必须是整数(或布尔)类型
- web-scraping - 使用 Rvest 抓取维基百科表格(错误)
- javascript - 无法使用ajax获取php全局变量