可视化命名颜色

这绘制了matplotlib中支持的命名颜色列表。 请注意,也支持xkcd颜色,但为简洁起见,此处未列出。

有关matplotlib中颜色的更多信息,请参阅:

  1. import matplotlib.pyplot as plt
  2. import matplotlib.colors as mcolors
  3. def plot_colortable(colors, title, sort_colors=True, emptycols=0):
  4. cell_width = 212
  5. cell_height = 22
  6. swatch_width = 48
  7. margin = 12
  8. topmargin = 40
  9. # Sort colors by hue, saturation, value and name.
  10. by_hsv = ((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
  11. for name, color in colors.items())
  12. if sort_colors is True:
  13. by_hsv = sorted(by_hsv)
  14. names = [name for hsv, name in by_hsv]
  15. n = len(names)
  16. ncols = 4 - emptycols
  17. nrows = n // ncols + int(n % ncols > 0)
  18. width = cell_width * 4 + 2 * margin
  19. height = cell_height * nrows + margin + topmargin
  20. dpi = 72
  21. fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
  22. fig.subplots_adjust(margin/width, margin/height,
  23. (width-margin)/width, (height-topmargin)/height)
  24. ax.set_xlim(0, cell_width * 4)
  25. ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
  26. ax.yaxis.set_visible(False)
  27. ax.xaxis.set_visible(False)
  28. ax.set_axis_off()
  29. ax.set_title(title, fontsize=24, loc="left", pad=10)
  30. for i, name in enumerate(names):
  31. row = i % nrows
  32. col = i // nrows
  33. y = row * cell_height
  34. swatch_start_x = cell_width * col
  35. swatch_end_x = cell_width * col + swatch_width
  36. text_pos_x = cell_width * col + swatch_width + 7
  37. ax.text(text_pos_x, y, name, fontsize=14,
  38. horizontalalignment='left',
  39. verticalalignment='center')
  40. ax.hlines(y, swatch_start_x, swatch_end_x,
  41. color=colors[name], linewidth=18)
  42. return fig
  43. plot_colortable(mcolors.BASE_COLORS, "Base Colors",
  44. sort_colors=False, emptycols=1)
  45. plot_colortable(mcolors.TABLEAU_COLORS, "Tableau Palette",
  46. sort_colors=False, emptycols=2)
  47. #sphinx_gallery_thumbnail_number = 3
  48. plot_colortable(mcolors.CSS4_COLORS, "CSS Colors")
  49. # Optionally plot the XKCD colors (Caution: will produce large figure)
  50. #xkcd_fig = plot_colortable(mcolors.XKCD_COLORS, "XKCD Colors")
  51. #xkcd_fig.savefig("XKCD_Colors.png")
  52. plt.show()

可视化命名颜色示例

可视化命名颜色示例2

可视化命名颜色示例3

参考

此示例中显示了以下函数,方法,类和模块的使用:

  1. import matplotlib
  2. matplotlib.colors
  3. matplotlib.colors.rgb_to_hsv
  4. matplotlib.colors.to_rgba
  5. matplotlib.figure.Figure.get_size_inches
  6. matplotlib.figure.Figure.subplots_adjust
  7. matplotlib.axes.Axes.text
  8. matplotlib.axes.Axes.hlines

下载这个示例