将 x 轴绘制为 MM:SS 而不是直方图中的整数

问题描述 投票:0回答:2

我有救护车响应时间数据(以秒为单位)。例如(32、158、36、459、830、396)。我能够制作一个 Matplotlib 直方图,将数据分为 60 秒增量。在 x 轴标签上,数据被标记为 0 - 60 - 120 - 180 等。我希望 x 轴标签显示 00:00 - 01:00 - 02:00 - 03:00 等。换句话说,作为整数值的秒,它应显示格式为 mm:ss 的秒。 下面的代码很接近,但我无法使其工作。下面的代码仅返回所有 bin 的 00:00。 如何将直方图的 x 轴标记为 mm:ss 而不是整数?

# import the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# generate a dataframe of values from 0 to 1800 (zero seconds to 1800 seconds which is 30 minutes)
df = pd.DataFrame(np.random.randint(0,1800, size=(1000, 1)), columns=list('A'))

start_value = 0 # the start value is zero seconds
end_value = 1800 # the end value is 1800 seconds (30 minutes)
increment_by_value = 60 # increment by one minute

# set up the nuts and bolts of the histogram
fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(8, 6.5)
ax = fig.add_subplot(111)

# generate a histogram
plt.hist(df.A, bins=np.arange(start_value, end_value, increment_by_value), color='Purple', label='Response Time', edgecolor = 'Gray', linewidth = 1.0)

# not sure how this works. I would hope that it formats 75 seconds to 01:15
myFmt = mdates.DateFormatter('%M:%S')
ax.xaxis.set_major_formatter(myFmt)

# the x ticks line up with the bars. In other words, every 60 seconds
plt.xticks(np.arange(start_value, end_value, increment_by_value), rotation='vertical')

# set up the title and the labels
plt.title("Cardiac Arrest Response Time" + '\n' + '(Interval in Seconds)')
plt.xlabel("Bins of 1 minute (in seconds)")
plt.ylabel("Calls")
plt.legend()
plt.show()
matplotlib axis axis-labels
2个回答
1
投票

我怀疑这个问题是因为

DateFormatter
期望自标准纪元以来的几天内输入。

解决这个问题的一个快速方法是完全删除

mdates
,并从
FuncFormatter
模块中定义一个简单的
matplotlib.ticker
。例如,替换这两行:

myFmt = mdates.DateFormatter('%M:%S')
ax.xaxis.set_major_formatter(myFmt)

import matplotlib.ticker as ticker

# Formatter function to convert seconds to MM:SS format
def seconds_to_minutes(seconds, pos):
    m = int(seconds // 60)
    s = int(seconds % 60)
    return f'{m:02d}:{s:02d}'

ax.xaxis.set_major_formatter(ticker.FuncFormatter(seconds_to_minutes))

Image showing plot with x-tick labels formatter as %M:%S


0
投票

感谢 tmdavison。这是为其他遇到此问题的人提供的完整示例。

# import the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

# generate a dataframe of values from 0 to 1800 (zero seconds to 1800 seconds which is 30 minutes)
df = pd.DataFrame(np.random.randint(0,1800, size=(1000, 1)), columns=list('A'))

start_value = 0 # the start value is zero seconds
end_value = 1800 # the end value is 1800 seconds (30 minutes)
increment_by_value = 60 # increment by one minute

# set up the nuts and bolts of the histogram
fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(8, 6.5)
ax = fig.add_subplot(111)

# generate a histogram
plt.hist(df.A, bins=np.arange(start_value, end_value, increment_by_value), color='Purple', label='Response Time', edgecolor = 'Gray', linewidth = 1.0)

# Formatter function to convert seconds to MM:SS format
def seconds_to_minutes(seconds, pos):
    m = int(seconds // 60)
    s = int(seconds % 60)
    return f'{m:02d}:{s:02d}'

ax.xaxis.set_major_formatter(ticker.FuncFormatter(seconds_to_minutes))

# the x ticks line up with the bars. In other words, every 60 seconds
plt.xticks(np.arange(start_value, end_value, increment_by_value), rotation='vertical')

# set up the title and the labels
plt.title("Cardiac Arrest Response Time" + '\n' + '(Interval in Seconds)')
plt.xlabel("Bins of 1 minute (in seconds)")
plt.ylabel("Calls")
plt.legend()
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.