在 matplotlib 中将 x 标题从秒转换为分钟

Convert x caption from seconds to minutes in mathplotlib

如何将 x-axis 中的标题从秒转换为分钟?

根据数据,我在几秒钟内生成了 10xx、20xx、30xx 和 40xx 的标签,因为数据在几秒钟内也有一个 x-label。

不幸的是,为了能够容易地对值进行分类,它应该是分钟,最好是偶数,例如每 30 或 60 分钟,具体取决于数据量。

x-axis 的标签应该是这样的: [60,120,180, 240,...]

df = pd.DataFrame(data)
df = df[['seconds', 'marker', 'data1', 'data2', 'data3']]
ax = df.set_index('seconds').plot(kind='bar', stacked=True, alpha=set_alpha)
ax.xaxis.set_major_locator(plt.MaxNLocator(5))
plt.plot(df.index, df['data1'], linestyle='solid', color='blue', alpha=0.4, label='data1')
plt.show()

数据示例:

seconds,marker,data1,data2,data3,data4
0,B,0,0,0,0
59,C,42,8,369000,0
74,B,42,8,369000,283041
121,B,42,8,369000,283041
179,B,42,8,369000,283041
239,B,42,8,369000,283041
304,B,42,8,369000,283041
360,B,42,8,369000,283041
377,A,42,8,369000,283041
420,B,42,8,369000,283041
493,B,42,8,369000,283041
540,B,42,8,369000,283041
600,B,42,8,369000,283041
659,B,42,8,369000,283041
719,B,64,8,412000,283041
780,B,64,8,412000,283041
840,B,64,8,412000,283041
880,A,64,8,412000,283041
900,B,64,8,412000,283041
961,B,64,8,412000,283041
1020,B,64,8,412000,283041
1079,B,64,8,412000,283041
1141,B,64,8,412000,283041
1200,B,64,8,412000,283041
1260,B,64,8,412000,283041
1320,B,64,8,412000,283041
1365,A,64,8,412000,283041
1382,B,64,8,412000,283041
1440,B,64,8,412000,283041
1498,B,64,8,412000,283041
1559,B,64,8,412000,283041
1621,B,64,8,412000,283041
1679,B,64,8,412000,283041
1740,B,64,8,412000,283041
1800,B,42,8,369000,283041
1830,A,42,8,369000,283041
1867,B,42,8,369000,283041
1921,B,42,8,369000,283041
1979,B,42,8,369000,283041
2040,B,42,8,369000,283041
2099,B,42,8,369000,283041
2159,B,42,8,369000,283041
2220,B,42,8,369000,283041
2272,A,42,8,369000,283041
2288,B,42,8,369000,283041
2341,B,42,8,369000,283041
2400,B,42,8,369000,283041
2460,B,42,8,369000,283041
2520,B,42,8,369000,283041
2579,B,42,8,369000,283041
2640,B,42,8,369000,283041
2700,B,42,8,369000,283041
2720,A,42,8,369000,283041
2759,B,42,8,369000,283041
2833,B,28,14,248000,260096
2880,B,28,14,248000,247808
2940,B,14,28,124000,123904
3000,B,0,42,0,0
3060,B,0,42,0,0
3120,B,0,42,0,0
3136,A,0,42,0,0
3180,B,0,42,0,0
3251,B,0,42,0,0
3267,D,0,42,0,0
3300,B,0,42,0,0
3359,B,0,42,0,0
3419,B,0,42,0,0
3538,B,0,0,0,0
3599,B,0,0,0,0
3643,C,140,4,1260000,0

我认为您可以尝试使用 .set_xticks(ticks, labels=labels)。这是一个例子:

import pandas as pd
import numpy as np

data = pd.read_csv(r"your_data_in_a_txt_file.txt")

t = data.seconds

max_t = np.max(t) # seconds
max_t = max_t/60 # minutes
max_t = max_t/30 # half hours
max_t = np.floor(max_t) # round downwards

ticks = np.arange(0,max_t+1) # Now we know have many ticks you need
labels = ["%.1f h" % (x/2) for x in ticks] # Generate tick labels
xticks = ticks*30*60 # and the actual positions of the ticks

fig, ax = plt.subplots()
for col in ["data1","data2","data3","data4"]:
    ax.plot(t, data[col], label=col)
ax.set_xticks(xticks, labels=labels)
plt.legend()
plt.show()