熊猫共享x轴和不完整的数据

时间:2017-10-19 00:32:15

标签: python pandas matplotlib

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

以下是一些测试数据和显示问题的图像。例如,X标签似乎是从最后一次调用绘图得到的,其次,第一天缺少数据的数据是在我想要它的第一天左侧绘制的。

我如何修复此情节,以便"最近"线是否正确移位,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

1 个答案:

答案 0 :(得分:1)

如果您想使用pandas

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

enter image description here