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

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

问题描述:

我在使用熊猫制作排名图时出现问题,其中一些数据可能是新的,只有数据开始在我的数据日期范围之间。熊猫分享x轴和不完整的数据

下面是一些测试数据和图像显示问题。首先,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

如果您想使用pandas

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

enter image description here