gpt4 book ai didi

python - X 轴上日历周 YYYYWW 的 Seaborn 多线图

转载 作者:行者123 更新时间:2023-12-01 06:46:10 26 4
gpt4 key购买 nike

我对seaborn线图的x轴值有一些问题:

import pandas as pd
import seaborn as sns

# data
df = pd.DataFrame(columns=['calendar_week', 'product_name', 'value'],
data=[['201850', 'product01', 1], ['201905', 'product01', 10], ['201910', 'product01', 7],
['201840', 'product02', 4], ['201911', 'product02', 9], ['201917', 'product02', 17], ['201918', 'product02', 12]])

# plot
sns.lineplot(data=df, x='calendar_week', y='value', hue='product_name');

如果calendar_week值是字符串,它会在第一个图表之后绘制第二个图表。如果calendar_week值为整数,则自动填充201852到201899之间的数据。仅使用给定的 calendar_week 值在一个排序的 x 轴上绘制两个图表的最佳方法是什么?

这是以 calendar_week 作为字符串的绘图: plot with x-axis values as string

这是以calendar_week为int的绘图: plot with x-axis values as int

感谢您的帮助。

最佳答案

这有点迂回,但我认为您需要首先将周数转换为实际日期、绘图,然后在 x 轴上使用自定义格式化程序再次显示周数。

df = pd.DataFrame(columns=['calendar_week', 'product_name', 'value'],
data=[['201850', 'product01', 1], ['201905', 'product01', 10], ['201910', 'product01', 7],
['201840', 'product02', 4], ['201911', 'product02', 9], ['201917', 'product02', 17], ['201918', 'product02', 12]])

df['date'] = pd.to_datetime(df.calendar_week+'0', format='%Y%W%w')
# plot
fig, ax = plt.subplots()
sns.lineplot(data=df, x='date', y='value', hue='product_name', ax=ax)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%W"))
fig.autofmt_xdate()

enter image description here

关于python - X 轴上日历周 YYYYWW 的 Seaborn 多线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59215629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com