【问题标题】:Setting different color for each class in a scatter plot which is made by using pd.pivot_table在使用 pd.pivot_table 制作的散点图中为每个类设置不同的颜色
【发布时间】:2017-07-15 23:57:48
【问题描述】:

我是 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)

与上面的不同,由于总和超过 Amount,一个类每个月只出现一次。

这是我的尝试:

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

我得到一个白点,而不是一个彩色的点,图例在图中的位置与您的图不同。此外,我无法正确看到年份标签。为什么?

【问题讨论】:

  • 抱歉,您能否解释一下它们到底出了什么问题,比如明确您不喜欢什么以及它应该是什么样子?我真的不明白第一个有什么问题。不过,您可能想查看seaborn,因为它是一个直接用于绘图的库并支持DataFrames
  • 在第一个图中,关联颜色点是错误的,而在第二个图中,标签只是由相应类名称的第一个字母而不是全名给出。这两个功能是我不喜欢的。谢谢

标签: python pandas matplotlib pivot-table


【解决方案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()

【讨论】:

  • 感谢您的回答。但是,只有在不操作数据框时才能使用它。首先,我想绘制一个 pivot_table 的结果。因为我使用 pivot_table 编写的内容并不那么相关。回到我的第一个目标,我尝试使用 sns.lmplot,但没有成功,我在上面的代码中添加了最后几行。有什么想法吗?
  • 对不起,我还是有点困惑你需要/想要什么(怪我的英语技能),但这是否可以接受[见上面的编辑]
  • 谢谢。我就是这个意思。我发布了使用您的代码获得的内容。我有一个白点,而不是一个彩色的,图例和你的图不在同一个地方(请见上图)。此外,我在 x 轴上看不到正确的年份标签。你知道为什么? Danke für deine Hilfe :)
  • 我不能说它为什么不同,但我发布了我的完整代码。如果您检查它,请告诉我结果是否仍然不同(我在 jupyter notebook 和脚本中进行了测试)
  • 您好,我刚刚复制了您的完整代码并使其运行。它还没有工作。很奇怪...我会尝试做一些研究来解决这个问题。当我明白会发生什么时,我会告诉你。谢谢
猜你喜欢
  • 1970-01-01
  • 2015-03-29
  • 2018-01-14
  • 2021-01-08
  • 2014-10-01
  • 1970-01-01
  • 2017-11-11
  • 2017-05-09
  • 2019-05-25
相关资源
最近更新 更多