Matplotlib Colorbar 不同于散点颜色?

Matplotlib Colorbar different from scatter colors?

下面的代码获取数据(下面复制了示例),并执行散点图,其中散点的形状取决于数据第一列的字符串值。 形状看起来是正确的,但是 Colorbar 不对应散点的归一化颜色! 直接调用 Colorbar 使其独立于绘图,而在循环内调用它只会显示多次...... 因此,Colorbars 需要是独立的(假的),但使用相同的数据进行校准。 我不确定的部分是:c=cmap.to_rgba(i + 1) 附上最终图片(img.png)

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

ax = plt.gca()

df = pd.read_csv('data.txt', delimiter="\t")
df.columns = ["type", "bv", "ron", "fom"]
df = df._convert(numeric=True)

norm = mpl.colors.Normalize(vmin=df.fom.min(), vmax=df.fom.max())
cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.hot)
cmap.set_array([])

for i in range(len(df.type)):
    if df.type[i] == 'a':
        sc = ax.scatter(df.bv[i], df.ron[i], marker='o', edgecolors='black', alpha=0.8, s=100, c=cmap.to_rgba(i + 1),
                        )
    if df.type[i] == 'b':
        sc = ax.scatter(df.bv[i], df.ron[i], marker='d', edgecolors='black', alpha=0.8, s=100, c=cmap.to_rgba(i + 1),
                        )
    if df.type[i] == 'c':
        sc = ax.scatter(df.bv[i], df.ron[i], marker='h', edgecolors='black', alpha=0.8, s=100, c=cmap.to_rgba(i + 1),
                        )
    if df.type[i] == 'd':
        sc = ax.scatter(df.bv[i], df.ron[i], marker='H', edgecolors='black', alpha=0.8, s=100, c=cmap.to_rgba(i + 1),
                        )
    if df.type[i] == 'e':
        sc = ax.scatter(df.bv[i], df.ron[i], marker='s', edgecolors='black', alpha=0.8, s=100, c=cmap.to_rgba(i + 1),
                        )
    if df.type[i] == 'u':
        sc = ax.scatter(df.bv[i], df.ron[i], marker='<', edgecolors='black', alpha=0.8, s=100, c=cmap.to_rgba(i + 1),
                        )

plt.yscale('log')
plt.xscale('log')
plt.grid(True, which="both", ls="-", alpha=0.1)
plt.colorbar(sc, ax=ax, norm=mpl.colors.Normalize(min(df.fom), max(df.fom)), cmap='hot', alpha=0.8)
plt.show()

图片:

final image

数据样本:

type    ron bv  fom
b   23  57  141,2608696
c   3238    535 88,39561458
d   11000   858 66,924
b   115 35,9    11,20704348
b   28  28  28
a   5   23  105,8
d   14500   977 65,82958621
d   3090    477 73,63398058
e   94  50  26,59574468
e   53  127 304,3207547
b   32,4    35,2    38,24197531
e   7,8 25  80,12820513
c   57  75  98,68421053
c   91  100 109,8901099
b   49  55  61,73469388
b   95  82  70,77894737
u   7,42    22,48   68,10652291

尝试将散点图重组为:

cmap = mpl.cm.hot
for ...
    sc = ax.scatter(df.bv[i], df.ron[i], marker='<', edgecolors='black',
                    alpha=0.8, s=100, c=df.fom[i], norm=norm, cmap=cmap)
    ....
fig.colorbar(sc)  # without the norm and cmap and call outside the loop