我在 Python Pandas 中有 DataFrame,如下所示:
date_col - 采用“datetime64”格式
銷售 - “int64”格式
date_col 銷售量 2019-01-05 100 2019-03-20 500 2019-04-28 290 ... ...
我需要創建時間序列圖并用單獨的顏色標記銷售額最高的 5 天。
目前我有如下代碼:
df['sales'].plot(linewidth=1.5,
grid = True,
marker="o",
linestyle="-",
markersize=4,
label="Daily sales",
color = "steelblue")
plt.xlabel("date")
plt.ylabel("sales")
plt.legend()
plt.show()
它給出了結果:

但作為最終結果,我需要如下所示:
- 垂直線代表銷售額最高的 5 天
- 銷售額最高的 5 天的年月日格式的日期

我怎樣才能在 Python 中做到這一點?我怎樣才能修改我的代碼或以其他方式做到這一點?
mrCopiCat 我使用了你的代碼,結果如下,為什么?

uj5u.com熱心網友回復:
好吧,您可以ax.annotate使用matplotlib. ax.vlines這是一個具有 5 個最大值的示例(我確實使用了簡單的 int 值作為日期(為了示例),但它肯定會與您的日期時間值一起使用):
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
# init figure and axis
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(title="maximum sales ...")
# sample df
data = {'date_col': list(range(20)), 'sales': [random.randint(1, 30) for _ in range(20)]}
df = pd.DataFrame.from_dict(data).set_index('date_col')
# plotting the df
df.plot(ax=ax)
# adding the lines
num_max = 5 # change this if you want more or less points
for row in df.sort_values(by='sales', ascending=False).iloc[:num_max].iterrows():
print(row[0], row[1])
xmax, ymax = row[0], row[1]
ax.vlines(xmax, 0, ymax, color="tab:red")
ax.annotate(f'{xmax}', xy=(xmax, ymax), xytext=(xmax, ymax 1), color="tab:red")
# setting size limit and plotting
ax.set_ylim(0,40) # change or remove that too
plt.show()
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/487188.html
標籤:Python 熊猫 约会时间 matplotlib 时间序列
