首页 > 解决方案 > matplotlib 在分组数据框的散点图中颜色错误

问题描述

我想为数据框中的每个组散点图具有不同颜色的熊猫数据框。下面的代码对我来说很好,除非我在数据框组中正好有 4 行。未应用于绘图的预定义颜色。

请看下面的例子:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

data = [
[3.28, 1, 0.202],
[3.05, 4, 0.006],
[1.20, 4, 0.234],
[3.44, 4, 0.052],
#[3.47, 4, 0.007],
#[2.79, 4, 0.029],
[3.44, 5, 0.0261],
[3.92, 5, 0.008],
[0.97, 5, 0.077],
#[1.58, 5, 0.043],
[0.03, 6, 0.441],
[0.75, 6, 0.099],
[0.68, 6, 0.093],
[0.68, 6, 0.083],
#[0.68, 6, 0.103], # uncomment this line and it works as expected
#[1.12, 6, 0.057]
]
columns = ['time', 'm', 'diff']
df = pd.DataFrame(data, columns=columns)
columns = ['time', 'm', 'diff']
df = pd.DataFrame(data, columns=columns)

colorMap = plt.cm.hsv(np.linspace(0, 1, 7))
fig, ax = plt.subplots()
print 'colormap'
for m, data in df.groupby('m'):
    print m, colorMap[m - 1]
    ax.scatter('time', 'diff', alpha=0.6, s=8*m**2, data=data,label=m, c= colorMap[m - 1])
vals = ax.get_yticks()
ax.set_yticklabels(['{:3.2f}%'.format(x*100) for x in vals])
ax.legend(title='m')
ax.grid(True)
plt.gcf().subplots_adjust(left=0.15)
handles, labels = ax.get_legend_handles_labels()
print 'facecolors'
for h in handles:
    print h.get_label(), h.get_facecolor()
plt.show()

在上面的示例中,组 m=6 有 4 个值。正如您在绘图输出和打印的 facecolors 中看到的那样,组 m=6 的颜色与颜色图不匹配。

输出:

colormap
1 [ 1.  0.  0.  1.]
4 [ 0.          1.          0.96470316  1.        ]
5 [ 0.          0.06250197  1.          1.        ]
6 [ 0.93345491  0.          1.          1.        ]
facecolors
1 [[ 1.   0.   0.   0.6]]
4 [[ 0.          1.          0.96470316  0.6       ]]
5 [[ 0.          0.06250197  1.          0.6       ]]
6 [[ 0.12156863  0.46666667  0.70588235  0.6       ]]

在此处输入图像描述

例如,组 m=6 中有 5 个成员,一切看起来都很好:

在此处输入图像描述

我怎样才能解决这个问题?

标签: pythonpython-2.7pandasmatplotlib

解决方案


scatter文件指出

请注意,c 不应是单个数字 RGB 或 RGBA 序列,因为它与要进行颜色映射的值数组无法区分。如果要为所有点指定相同的 RGB 或 RGBA 值,请使用具有单行的二维数组。

因此

c = [colorMap[m - 1]] 

按预期工作。

colormap
1 [ 1.  0.  0.  1.]
4 [ 0.          1.          0.96470316  1.        ]
5 [ 0.          0.06250197  1.          1.        ]
6 [ 0.93345491  0.          1.          1.        ]
facecolors
1 [[ 1.   0.   0.   0.6]]
4 [[ 0.          1.          0.96470316  0.6       ]]
5 [[ 0.          0.06250197  1.          0.6       ]]
6 [[ 0.93345491  0.          1.          0.6       ]]

在此处输入图像描述


推荐阅读