AttributeError:'模块'对象没有属性' BASE_COLORS'

时间:2017-02-02 17:02:32

标签: python matplotlib colors

感谢您的时间!我的代码是在python中,我想绘制一些图形来查看图形中的颜色。代码是:

"""
Visualization of named colors.

Simple plot example with the named colors and its visual representation.
"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import six

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors


colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)

# Sort by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                for name, color in colors.items())

# Get the sorted color names.
sorted_names = [name for hsv, name in by_hsv]

n = len(sorted_names)
ncols = 4
nrows = int(np.ceil(1. * n / ncols))

fig, ax = plt.subplots(figsize=(8, 5))

X, Y = fig.get_dpi() * fig.get_size_inches()

# row height
h = Y / (nrows + 1)
# col width
w = X / ncols

for i, name in enumerate(sorted_names):
    col = i % ncols
    row = int(i / ncols)
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.8),
            horizontalalignment='left',
            verticalalignment='center')

    ax.hlines(
        y + h * 0.1, xi_line, xf_line, color=colors[name], linewidth=(h * 0.6))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.show()

但程序不可执行,并报告以下错误消息:

AttributeError:' module'对象没有属性' BASE_COLORS'。我该如何运行该程序?

3 个答案:

答案 0 :(得分:1)

将matplotlib升级到版本2.0+然后这应该工作。 BASE_COLORS和CSS4_COLORS都在此定义。

答案 1 :(得分:0)

代码是matplotlib页面中众所周知的named_colors example

根据您运行的matplotlib的版本,该示例将会或不会起作用。但是,之前版本的示例仍然可用:

v2.0:http://matplotlib.org/examples/color/named_colors.html
v1.5:http://matplotlib.org/1.5.1/examples/color/named_colors.html
v x y z http://matplotlib.org/x.y.z/examples/color/named_colors.html

答案 2 :(得分:0)

将matplotlib升级到2.0+版本。在那里定义了BASE_COLORS和其他内容。

要升级,请使用命令:

$python -m pip install --user matplotlib --upgrade