gpt4 book ai didi

python - 共享 x 轴且数据不完整的 Pandas

转载 作者:太空宇宙 更新时间:2023-11-03 14:37:34 24 4
gpt4 key购买 nike

我在使用 Pandas 制作排名图表时遇到问题,其中一些数据可能是新的,并且数据仅从数据日期范围的中间开始。

下面是一些测试数据和显示问题的图像。首先,X 标签似乎源自最后一次对绘图的调用,其次,第一天缺少数据的数据绘制在距离我想要的位置还剩 1 天的位置。

如何修复此图,以便“最近”线正确移动并且 X 轴上的日期也正确?

import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
from matplotlib.ticker import MaxNLocator

TESTDATA=StringIO("""
2017-10-10 A 30
2017-10-10 B 40
2017-10-10 C 60
2017-10-10 D 20

2017-10-11 A 60
2017-10-11 B 20
2017-10-11 C 30
2017-10-11 D 10
2017-10-11 Recent 50

2017-10-12 A 40
2017-10-12 B 20
2017-10-12 C 17
2017-10-12 D 15
2017-10-12 Recent 45
""")

# recent

headers = ['Date','Name','Downloads']
df = pd.read_csv(TESTDATA, sep='\t', names=headers)
df["Ranking"] = df.groupby(["Date"])["Downloads"].rank(method="first", ascending=False)
print(df)
df.set_index('Date', inplace=True)
fig, ax = plt.subplots(figsize=(10, 5), sharex=True)
labels = []

for key, grp in df.groupby(['Name']):
#grp = grp[grp.Ranking <=3]
grp.plot(ax=ax, kind='line', y='Ranking', linewidth=4, sharex=True)
labels.append(key)
lines, _ = ax.get_legend_handles_labels()
ax.legend(lines, labels, loc='best')
plt.gca().invert_yaxis()
ax.xaxis
#ax.set_ylim(4.5, 0.5)

ax.yaxis.set_major_locator(MaxNLocator(integer=True))

plt.xlabel('Date')
plt.ylabel('Rank')
plt.title('Daily Download Ranks')
plt.show()

enter image description here

最佳答案

如果您想使用pandas

df.pivot('Date','Name','Downloads').rank(method="first", ascending=False,axis=1).plot()

enter image description here

关于python - 共享 x 轴且数据不完整的 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46821227/

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