如何在matplotlib中使用日期时间标签标记毫秒轴

2024-06-21 20:13:19 发布

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

我有一个时间线图。我在上面画了很多矩形,当时间以毫秒为单位时,这很容易做到。但是x轴的标签是数字的,我宁愿它们是日期。我可以用df['timestamp'] = pandas.to_datetime(df['timestamp'])转换时间戳来修复x轴标签,但矩形绘图数学中断,因为我无法从类似rect = [(t - 59000, h - 0.4), (t - 59000, h + 0.4), (t, h + 0.4), (t, h - 0.4), (t - 59000, h - 0.4)]; bars.append(rect); bars = PolyCollection(bars)的日期时间中减去毫秒

我认为改变轴的标记方式是最简单的。我怎样才能让它不再试图绘制大量的长数字,而是绘制漂亮的日期字符串呢

enter image description here

我只想将x轴标签显示为日期时间,而不是这些可怕的无法读取的数字

import pandas
from matplotlib import pyplot
from matplotlib.collections import PolyCollection
from matplotlib.ticker import MultipleLocator

df = pandas.read_csv('thing.csv')

vert = {"upright":1, "supine":2, "lying_left":3, "prone":4, "lying_right":5, "unknown":6}

fig, (ax1) = pyplot.subplots(1, 1, figsize=(15,5))

# first plot of positions over time
# get the computed body positions as bars
bars = []
colors = []
for i,row in df.iterrows():
    h = vert[row['body_position']]
    t = row['timestamp']
    
    rect = [(t - 59000, h - 0.4), (t - 59000, h + 0.4), (t, h + 0.4), (t, h - 0.4), (t - 59000, h - 0.4)]
    bars.append(rect)
    colors.append("C" + str(h-1))

bars = PolyCollection(bars, facecolors=colors)
ax1.add_collection(bars)

ax1.autoscale()
ax1.xaxis.set_major_locator(MultipleLocator(60000))
#ax1.set_xticklabels([''], rotation=90)
#ax1.xaxis.set_major_formatter(dates.DateFormatter("%B-%d\n%H:%M"))

ax1.set_yticks(sorted(vert.values()))
ax1.set_yticklabels(sorted(vert, key=vert.get))

pyplot.tight_layout()
pyplot.show()

以下是一些用于生成绘图的示例数据:

timestamp,incline_angle,rotation_angle,body_position
1631311140000,,,unknown
1631311200000,,,unknown
1631311260000,2.698802523069221,175.23174346257375,upright
1631311320000,3.79042308483573,167.83999245871857,upright
1631311380000,1.5175027051794074,179.61841112309935,upright
1631311440000,3.975208379737314,171.42631984353366,upright
1631311500000,1.1885374082444298,86.49027321064233,upright
1631311560000,4.810193480680129,21.462454182905063,upright
1631311620000,,,unknown
1631311680000,88.69449620162857,-178.52467261213772,supine
1631311740000,76.13842375737948,-176.28409623055694,supine
1631311800000,56.72313055674839,-171.72681198213715,supine
1631311860000,,,unknown
1631311920000,77.82676616765237,-72.18362857622509,lying_right
1631311980000,81.8046648695628,-46.69883607858903,lying_right
1631312040000,90.30495291582416,-11.324002429040227,prone
1631312100000,,,unknown
1631312160000,108.06979339334902,108.76621826399024,lying_left
1631312220000,,,unknown
1631312280000,,,unknown
1631312340000,,,unknown
1631312400000,117.55244721818904,165.87088640221413,unknown
1631312460000,0.5689364636363466,171.6313935247612,upright
1631312520000,10.566662943419471,-10.860907998962931,upright
1631312580000,24.244743971818696,-3.2077664692605854,upright
1631312640000,24.790924330066783,-5.473576795955548,upright
1631312700000,27.581635762266146,-6.965410020736653,upright

Tags: rectimportdf时间标签timestampunknownset
2条回答

你要找的是格式化你的xaxis 您可以使用以下选项:

import matplotlib.dates as mdates
fig, ax = plt.subplots()
myFmt = mdates.DateFormatter("%B-%d\n%H:%M")
ax.xaxis.set_major_formatter(myFmt)

然后在数据上绘制任意类型的绘图。 完整文档here。对于特定的日期时间格式代码,也可以使用this

好的,太好了!我能够重现您的代码,并添加了几行代码,以获得您正在寻找的@PavelKomarov结果

import pandas
from matplotlib import pyplot
from matplotlib.collections import PolyCollection
from matplotlib.ticker import MultipleLocator
import matplotlib.pyplot as plt

df = pandas.read_csv('thing.csv')

vert = {"upright":1, "supine":2, "lying_left":3, "prone":4, "lying_right":5, "unknown":6}

fig, (ax1) = pyplot.subplots(1, 1, figsize=(15,5))

# first plot of positions over time
# get the computed body positions as bars
bars = []
colors = []
for i,row in df.iterrows():
    h = vert[row['body_position']]
    t = row['timestamp']
    
    rect = [(t - 59000, h - 0.4), (t - 59000, h + 0.4), (t, h + 0.4), (t, h - 0.4), (t - 59000, h - 0.4)]
    bars.append(rect)
    colors.append("C" + str(h-1))

bars = PolyCollection(bars, facecolors=colors)
ax1.add_collection(bars)

ax1.autoscale()
ax1.xaxis.set_major_locator(MultipleLocator(60000))

ax1.set_yticks(sorted(vert.values()))
ax1.set_yticklabels(sorted(vert, key=vert.get))

ax1.set_xticklabels([pd.to_datetime(x).strftime("%Y/%m/%d") for x in ax1.get_xticks()])
plt.xticks(rotation=90)

pyplot.tight_layout()
pyplot.show()

我添加的另外两行是:

ax1.set_xticklabels([pd.to_datetime(x).strftime("%Y/%m/%d") for x in ax1.get_xticks()])
plt.xticks(rotation=90)

xaxis上的时间戳减少到毫秒,因此我将它们格式化为YYYY/MM/DD。您可以使用this更改格式

让我知道这是否是你要找的

相关问题 更多 >