gpt4 book ai didi

python - matplotlib分组数据框散点图中的颜色错误

转载 作者:行者123 更新时间:2023-11-30 22:11:08 28 4
gpt4 key购买 nike

我想为数据框中的每个组绘制一个具有不同颜色的 pandas 数据框。下面的代码对我来说效果很好除非当我在数据帧组中正好有 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()

在上面的示例中,我有 4 个组 m=6 的值。正如您在绘图输出和打印的面颜色中看到的,组 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 ]]

enter image description here

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

enter image description here

我该如何解决这个问题?

最佳答案

The scatter documentation

Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2-D array with a single row.

因此

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 ]]

enter image description here

关于python - matplotlib分组数据框散点图中的颜色错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51516790/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com