matplotlib text()未显示在打印中

2024-06-01 00:52:56 发布

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

我无法在绘图中显示文字,axhline()显示文字,但无法显示文字()。我对熊猫和matplotlib还不熟悉,显然我不了解一些东西

plot image

# df is a pandas Dataframe

df_last_24 = df[df['Date']>=(dt.datetime.now()-dt.timedelta(hours=24))]

ax = df_last_24.plot.line(x="Date",title="Air Qualty Index over the last 24 hours")

# Define the date format
years_fmt = mdates.DateFormatter('%I:%M %p')
ax.xaxis.set_major_formatter(years_fmt)


plot.axhline(linewidth=4,y=300, color='#731425', linestyle='-')
plot.text(0, 300, 'Hazardous', fontsize=10, va='center', ha='left', backgroundcolor='w')

plot.axhline(linewidth=4,y=200, color='#8c1a4b', linestyle='-')
plot.text(0, 200, 'Very Unhealthy', fontsize=10, va='center', ha='left', backgroundcolor='w')

plot.axhline(linewidth=4,y=150, color='#951d47', linestyle='-')
plot.text(0, 150, 'Unhealthy', fontsize=10, va='center', ha='left', backgroundcolor='w')

plot.axhline(linewidth=4,y=100, color='#e23127', linestyle='-')
plot.text(0, 100, 'Unhealthy to Sensitive Groups', fontsize=10, va='center', ha='left', backgroundcolor='w')

plot.axhline(linewidth=4,y=50, color='#f29d3a', linestyle='-')
plot.text(0, 50, 'Moderate', fontsize=10, va='center', ha='left', backgroundcolor='w')

plot.show(block=True)


Tags: textdfplotleftcolorlastcenter文字
2条回答

plt.axhline()plt.是正确的描述。其他图表可能因缺少提供的数据而受到影响。请检查一下这个

import matplotlib.pyplot as plt

plt.axhline(linewidth=4,y=300, color='#731425', linestyle='-')
plt.text(0, 300, 'Hazardous', fontsize=10, va='center', ha='left', backgroundcolor='w')

plt.axhline(linewidth=4,y=200, color='#8c1a4b', linestyle='-')
plt.text(0, 200, 'Very Unhealthy', fontsize=10, va='center', ha='left', backgroundcolor='w')

plt.axhline(linewidth=4,y=150, color='#951d47', linestyle='-')
plt.text(0, 150, 'Unhealthy', fontsize=10, va='center', ha='left', backgroundcolor='w')

plt.axhline(linewidth=4,y=100, color='#e23127', linestyle='-')
plt.text(0, 100, 'Unhealthy to Sensitive Groups', fontsize=10, va='center', ha='left', backgroundcolor='w')

plt.axhline(linewidth=4,y=50, color='#f29d3a', linestyle='-')
plt.text(0, 50, 'Moderate', fontsize=10, va='center', ha='left', backgroundcolor='w')

plt.show(block=True)

enter image description here

问题是数据帧图中的x坐标是时间。使用min()和datestr2num()似乎可以解决这个问题

# Find Date/Time Range
column = df_last_24['Date/Time'].dt.strftime('%a %b %d %H:%M')
subtitle = column.min() + " - " +column.max()
text_x = mdates.datestr2num(column.min())

...

# Add Level lines and Labels
ax.axhline(linewidth=4,y=300, color='#731425', linestyle='-')
ax.text(text_x, 300, 'Hazardous', fontsize=10, va='center', ha='left', backgroundcolor='w')

相关问题 更多 >