使用 matplotlib 绘制一些数据时,我发现一个有点烦人的问题。
如下面的示例输出所示,x 轴的格式有点出乎意料。
标签是(例如)04 12:30
。是该04
月中的某一天。
提供代码和数据来重现该图,并附加在该问题的末尾。
为什么 x 轴的格式是这样的?我能做些什么来“修复”它?(我不希望显示该月的某一天,而且我特别不希望将其格式设置为“04”。)
代码
运行代码:python3 example.py
# example.py
import matplotlib.pyplot as plt
import pandas
df = pandas.read_json('data.json')
print(df.head())
fig, ax1 = plt.subplots(figsize=(12, 8))
ax1.plot(df['column_name'], label='My data')
ax1.set_xlabel('Timestamp')
ax1.set_ylabel('Value')
ax1.grid(True)
ax1.legend()
plt.title('Example')
plt.tight_layout()
plt.savefig('example.png')
数据
将此文件另存为data.json
{"column_name":{"1649073600000":174.79,"1649073660000":174.8,"1649073720000":174.79,"1649073780000":174.76,"1649073840000":174.69,"1649073900000":174.7,"1649073960000":174.69,"1649074020000":174.65,"1649074140000":174.67,"1649074200000":174.7,"1649074260000":174.74,"1649074320000":174.65,"1649074380000":174.69,"1649074440000":174.65,"1649074500000":174.7,"1649074560000":174.74,"1649074680000":174.72,"1649074740000":174.7,"1649074860000":174.7,"1649074920000":174.71,"1649074980000":174.75,"1649075040000":174.76,"1649075100000":174.73,"1649075160000":174.76,"1649075220000":174.7,"1649075280000":174.66,"1649075340000":174.61,"1649075400000":174.63,"1649075460000":174.65,"1649075520000":174.7,"1649075580000":174.69,"1649075640000":174.63,"1649075760000":174.66,"1649075820000":174.63,"1649075880000":174.58,"1649075940000":174.5,"1649076000000":174.52,"1649076060000":174.55,"1649076120000":174.55,"1649076180000":174.54,"1649076240000":174.48,"1649076300000":174.45,"1649076360000":174.38,"1649076420000":174.22,"1649076480000":174.21,"1649076540000":174.15,"1649076660000":174.25,"1649076720000":174.3,"1649076780000":174.28,"1649076840000":174.26,"1649076900000":174.25,"1649076960000":174.23,"1649077020000":174.21,"1649077080000":174.25,"1649077140000":174.26,"1649077200000":174.27}}
DateFormatter
在这里效果很好:输出: