python - 将归一化标量颜色图应用于 matplotlib 图,仍然获得默认颜色

标签 python matplotlib colormap

我正在尝试让绘图具有与默认颜色图不同的颜色图。 dark2 颜色图看起来对我的数据来说是最好的,但它都是以默认颜色显示的。我错过了什么?

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pylab import get_cmap

data = [{'a': 1, 'b': 1, 'c': 2, 'd': 0},{'a': 1, 'b': 1, 'c': 2, 'd': 0},
        {'a': 1, 'b': 1, 'c': 1, 'd': 2},{'a': 1, 'b': 2.5, 'c': 1, 'd': 2},
        {'a': 1.7, 'b': 2.1, 'c': 2, 'd': 0.2},{'a': 1.7, 'b': 2.1, 'c': 2, 'd': 0.2}]
cm = get_cmap('Dark2')

cnorm = matplotlib.colors.Normalize(vmin=0, vmax=len(data))
smap = matplotlib.cm.ScalarMappable(norm=cnorm, cmap=cm)
_fig, ax = plt.subplots(1, 1, figsize=(18, 8))
for lx in range(len(ax.axes.lines)):
    ax.axes.lines[lx].set_color(smap.to_rgba(lx))
    print('setting color for %i to %s' % (lx, smap.to_rgba(lx)))

frm = pd.DataFrame(data)
frm.plot(ax=ax)

plt.show()

最佳答案

您正在空列表上设置颜色。只需移动代码即可:

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

%matplotlib inline

data = [
    {'a': 1, 'b': 1, 'c': 2, 'd': 0},
    {'a': 1, 'b': 1, 'c': 2, 'd': 0},
    {'a': 1, 'b': 1, 'c': 1, 'd': 2},
    {'a': 1, 'b': 2.5, 'c': 1, 'd': 2},
    {'a': 1.7, 'b': 2.1, 'c': 2, 'd': 0.2},
    {'a': 1.7, 'b': 2.1, 'c': 2, 'd': 0.2}
]
cm = matplotlib.cm.Dark2

cnorm = matplotlib.colors.Normalize(vmin=0, vmax=len(data))
smap = matplotlib.cm.ScalarMappable(norm=cnorm, cmap=cm)
_fig, ax = plt.subplots(1, 1, figsize=(18, 8))

frm = pd.DataFrame(data)
frm.plot(ax=ax, legend=False)  # legend=False b/c we haven't tweaked colors yet

for lx in range(len(ax.axes.lines)):
    ax.axes.lines[lx].set_color(smap.to_rgba(lx))

    # now this will actually print something
    print('setting color for %i to %s' % (lx, smap.to_rgba(lx)))

ax.legend()  # and now do the legend

关于python - 将归一化标量颜色图应用于 matplotlib 图,仍然获得默认颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26068491/

相关文章:

python - 由于ffmpeg不可用,matplotlib动画ArtistAnimation失败

python - 如何在 matplotlib 散点图中标准化颜色图?

javascript - 推送通知无法按照示例中列出的那样工作

Python- Pandas : AttributeError: 'numpy.ndarray' object has no attribute 'start'

python - 使用 PySide 并从 QtGui.QColorDialog 获取 "live update"

python - 从两个 pandas groupby 对象绘制堆叠条形图?

python - 如何向 subplot2grid 添加颜色条

python - 计算列表中的重复项,并将该数字放入子列表中?

python - 在Numpy和OpenCV2中替换3D子矩阵