使用pd.pivot_table

时间:2017-07-14 17:14:53

标签: python pandas matplotlib pivot-table

我是Pandas及其图书馆的新手。通过使用以下代码,我可以在“月”与“数量”平面中制作我的“类”的散点图。因为我考虑不止一个班级,我想用颜色来区分每个班级,并在图中看到一个图例。

在我的第一次尝试之下,可以为每个具有不同颜色的给定类生成点,但它不能生成正确的图例。相反,第二次尝试可以生成正确的图例,但标签不正确。我确实可以看到每个类名的第一个字母。此外,第二次尝试绘制了与班级数量一样多的数字。我想知道如何纠正我的尝试。有任何想法吗?建议?提前致谢。

PS 即可。我想用

colors = itertools.cycle(['gold','blue','red','chocolate','mediumpurple','dodgerblue']) 

同样,我可以决定颜色。我无法做到。

尝试:

import pandas as pd
import numpy as np
import random 
from matplotlib import pyplot as plt 
import matplotlib.cm as cm

np.random.seed(176)
random.seed(16)

df = pd.DataFrame({'class': random.sample(['living room','dining room','kitchen','car','bathroom','office']*10, k=25),
                   'Amount': np.random.sample(25)*100,
                   'Year': random.sample(list(range(2010,2018))*50, k=25),
                   'Month': random.sample(list(range(1,12))*100, k=25)})

print(df.head(25))

print(df['class'].unique())

for cls1 in df['class'].unique():
    test1= pd.pivot_table(df[df['class']==cls1], index=['class', 'Month', 'Year'], values=['Amount'])
    print(test1)

colors = cm.rainbow(np.linspace(0,2,len(df['class'].unique()))) 

fig, ax = plt.subplots(figsize=(8,6))

for cls1,c in zip(df['class'].unique(),colors): 
    # SCATTER PLOT
    test = pd.pivot_table(df[df['class']==cls1], index=['class', 'Month', 'Year'], values=['Amount'], aggfunc=np.sum).reset_index()    
    test.plot(kind='scatter', x='Month',y='Amount', figsize=(16,6),stacked=False,ax=ax,color=c,s=50).legend(df['class'].unique(),scatterpoints=1,loc='upper left',ncol=3,fontsize=10.5)
plt.show() 


for cls2,c in zip(df['class'].unique(),colors): 
    # SCATTER PLOT
    test = pd.pivot_table(df[df['class']==cls2], index=['class', 'Month', 'Year'], values=['Amount'], aggfunc=np.sum).reset_index()    
    test.plot(kind='scatter', x='Month',y='Amount', figsize=(16,6),stacked=False,color=c,s=50).legend(cls2,scatterpoints=1,loc='upper left',ncol=3,fontsize=10.5)
    plt.show() 

enter image description here

最新代码

我想通过散点图绘制以下代码。

for cls1 in df['class'].unique():
    test3= pd.pivot_table(df[df['class']==cls1], index=['class', 'Month'], values=['Amount'], aggfunc=np.sum)
    print(test3)

与上述不同,由于金额总和,每个月只出现一次。

这是我的尝试:

for cls2 in df['class'].unique():
    test2= pd.pivot_table(df[df['class']==cls2], index=['class','Year'], values=['Amount'], aggfunc=np.sum).reset_index()
    print(test2)
    sns.lmplot(x='Year' , y='Amount', data=test2, hue='class',palette='hls', fit_reg=False,size= 5, aspect=5/3, legend_out=False,scatter_kws={"s": 70})
plt.show() 

这给了我每个班级的一个情节。第一个(class = car)的一部分显示不同的颜色,其他部分似乎没问题。尽管如此,我想在所有课程中只有一个情节。

在Marvin Taschenberger的有用帮助之后,这是最新的结果:

enter image description here

我得到一个白色点而不是彩色点,并且图中的图形与图形有不同的位置。而且我无法正确看到年份标签。为什么呢?

1 个答案:

答案 0 :(得分:1)

解决问题的一个简单方法(不幸的是没有解决)是因为简单的线路让seaborn处理繁重的工作

sns.lmplot(x='Month' , y='Amount', data=df, hue='class',palette='hls', fit_reg=False,size= 8, aspect=5/3, legend_out=False)

您还可以为palette

插入其他颜色

编辑:那怎么样: `

import pandas as pd
import numpy as np
import random 
from matplotlib import pyplot as plt 
import seaborn as sns 

np.random.seed(176)
random.seed(16)

df = pd.DataFrame({'class': random.sample(['living room','dining room','kitchen','car','bathroom','office']*10, k=25),
               'Amount': np.random.sample(25)*100,
               'Year': random.sample(list(range(2010,2018))*50, k=25),
               'Month': random.sample(list(range(1,12))*100, k=25)})

frame = pd.pivot_table(df, index=['class','Year'], values=['Amount'], aggfunc=np.sum).reset_index()
sns.lmplot(x='Year' , y='Amount', data=frame, hue='class',palette='hls', fit_reg=False,size= 5, aspect=5/3, legend_out=False,scatter_kws={"s": 70})
plt.show()

enter image description here