gpt4 book ai didi

Python plot y 轴平均标签不会显示并且日期在所有 crowder

转载 作者:行者123 更新时间:2023-12-05 04:44:45 27 4
gpt4 key购买 nike

我想为红色 y 轴平均线添加一个标签,但它不会显示为标签。此外,数据集中的所有日期都是 crowdet

这是我的代码:

def plot_data(measurement):


df = pd.read_csv("out.csv")
date = df["date"]
value = df[measurement]

plt.plot(date, value, label=host[0:7] + ", " + measurement + ", " + date_til[0:10] + " " + date_from[11:19] + "-" + date_til[11:19])
plt.title(measurement)
plt.xlabel("date")
plt.ylabel(measurement)
plt.legend()
plt.xticks(rotation=45)

average = df[measurement].mean()

plt.axhline(y=average, color='r', linestyle='-', label="average Ø ≈ " + str(average))

fig = plt.gcf()
fig.set_size_inches(18.5, 10.5, forward=True)

#today = date.today()
#print(today)
filename = "plots/plot_" + date_from[0:10] + ".png"

fig.savefig(filename, dpi=100)

print("\rPlot: Done ✔️")

这是情节的结果: broken_plot

最佳答案

为了在图例中显示 average Ø ≈ ... 标签,您需要在 ax.axhline 之后调用 plt.legend:

...

average = df[measurement].mean()

plt.axhline(y=average, color='r', linestyle='-', label="average Ø ≈ " + str(average))

plt.legend()

...

x 轴标签拥挤发生在您将 x 轴绘制为 str 代替 datetime 时,因此您需要使用 pandas.to_datetime 进行此转换首先:

df = pd.read_csv(r'data/data.csv')

fig, ax = plt.subplots()

ax.plot(df['date'], df['value'])

plt.show()

enter image description here

df = pd.read_csv(r'data/data.csv')
df['date'] = pd.to_datetime(df['date'])

fig, ax = plt.subplots()

ax.plot(df['date'], df['value'])

plt.show()

enter image description here


您可以进一步自定义 x 轴刻度:

import matplotlib.dates as md

# set spacing between ticks
ax.xaxis.set_major_locator(md.HourLocator(interval = 3))

# set tick label format
ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))

# set tick label rotation to 45°
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 45)

enter image description here

关于Python plot y 轴平均标签不会显示并且日期在所有 crowder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69280482/

27 4 0