python - 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 个成员,一切看起来都很好:
我怎样才能解决这个问题?
解决方案
请注意,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 ]]
推荐阅读
- python - 在 Python 中为 Terraform 应用程序初始化一个新的 CDKTF
- tensorflow - 如何在使用 Residual Skip Connections(基于 ResNet 的自动编码器)的 Keras(tensorflow.keras)中构建自动编码器/U-Net?
- javascript - 如何在 javascript 或 jquery 中提交一组值?
- javascript - 将带有图像的 html 表导出到 xlsx - Javascript
- node.js - 如何在 Google Cloud Function 中通过 HTTP 响应发送大文件
- swift - Swift - 如何使用枚举字典初始化变量?
- r - 如何更改颜色索引中的中间值?
- selenium - 如何使用 java 处理 Selenium 中的自动建议?
- udp - 有没有办法通过 udp 检查来自源的 rtp 流?
- mysql - “一般错误:1364 字段‘user_id’没有默认值”Laravel