python - Matplotlib 最大刻度显示前几个刻度
问题描述
我正在尝试绘制约 100 天的时间序列。为了提高可读性,我想限制 x 轴刻度的数量。但是,两者plt.locator_params(axis='x', nbins=6)
都只ax.xaxis.set_major_locator(plt.MaxNLocator(10))
显示前几个滴答声,而不是每个第 n 个滴答声。下面的图应该在 05-23 和 07-21(60 个间隔)之间均匀分布刻度,而不是从 05-23 开始的 6 个刻度
plt.stackplot(df.iloc[:,0], df.iloc[:, 1])
plt.legend(loc='upper left')
plt.xlabel("This axis actually goes from 05-23 to 07-21")
plt.locator_params(axis='x', nbins=6)
使用的数据框
id month-day result
0 05 - 23 78
1 05 - 24 154
2 05 - 25 138
3 05 - 26 176
4 05 - 27 142
5 05 - 28 122
6 05 - 29 199
7 05 - 30 202
8 05 - 31 194
9 06 - 01 166
10 06 - 02 141
11 06 - 03 136
12 06 - 04 108
13 06 - 05 149
14 06 - 06 168
15 06 - 07 182
16 06 - 08 192
17 06 - 09 147
18 06 - 10 133
19 06 - 11 109
20 06 - 12 115
21 06 - 13 124
22 06 - 14 172
23 06 - 15 204
24 06 - 16 131
25 06 - 17 145
26 06 - 18 128
27 06 - 19 179
28 06 - 20 170
29 06 - 21 385
30 06 - 22 427
31 06 - 23 404
32 06 - 24 471
33 06 - 25 334
34 06 - 26 557
35 06 - 27 291
36 06 - 28 337
37 06 - 29 718
38 06 - 30 658
39 07 - 01 524
40 07 - 02 406
41 07 - 03 744
42 07 - 04 941
43 07 - 05 919
44 07 - 06 855
45 07 - 07 740
46 07 - 08 612
47 07 - 09 592
48 07 - 10 797
49 07 - 11 804
50 07 - 12 1072
51 07 - 13 1141
52 07 - 14 1028
53 07 - 15 841
54 07 - 16 822
55 07 - 17 1157
56 07 - 18 1356
57 07 - 19 1031
58 07 - 20 1068
59 07 - 21 992
解决方案
根本问题似乎是您生成的图表有一个 FixedLocator 和一个 FixedFormatter。仅更换定位器但保持固定的格式化程序将导致无用的结果。
由于您在这里使用日期,因此在图中使用日期是有意义的。然后,您可以使用matplotlib.dates
.
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates
df = pd.read_csv("data/month-day-data.txt", sep="\s\s+", engine="python")
df["month-day"] = pd.to_datetime(df["month-day"], format="%m - %d")
plt.stackplot(matplotlib.dates.date2num(df["month-day"]), df["result"])
plt.xlabel("This axis actually goes from 05-23 to 07-21")
plt.gca().xaxis.set_major_locator(matplotlib.dates.AutoDateLocator())
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%m - %d"))
plt.show()
推荐阅读
- ios - 如何防止事件被迅速发送到哨兵(iOS)
- vue.js - 如何修复'npm:无效的配置对象。Webpack 已使用与 API 模式不匹配的配置对象进行初始化。
- bash - Oracle expdp bash sh 使用 at 传递密码
- mysql - 两个数字之间的序列和MySQL
- asp.net-core - 如何修复“AADSTS90102:‘redirect_uri’值必须是有效的绝对 Uri。” Microsoft Graph 中的错误
- c# - 使用 NAudio 混合两个音频文件
- c++ - 对于gtest,如何模拟具有相同名称但类型不同的方法
- c# - 如何从每个 KVP 中获取数据
- kubernetes - 将 Windows Server 加入/扩展至 Istio Mesh?
- macos - 无法在 macOS 10.15 上启动新的 FileProvider 扩展