【问题标题】:Use a colourmap to change line colour使用颜色图更改线条颜色
【发布时间】:2014-02-27 12:26:42
【问题描述】:

我有很多不同的文件 (10-20),我从中读取 x 和 y 数据,然后绘制成一条线。 目前我有标准颜色,但我想改用颜色图。 我查看了许多不同的示例,但无法正确调整我的代码。 我希望使用颜色图(例如 gist_rainbow 即离散颜色图)在每条线之间(而不是沿线)改变颜色 下图是我目前可以实现的。

这是我尝试过的:

import pylab as py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc, rcParams

numlines = 20
for i in np.linspace(0,1, numlines):
    color1=plt.cm.RdYlBu(1)
    color2=plt.cm.RdYlBu(2)

# Extract and plot data
data = np.genfromtxt('OUZ_QRZ_Lin_Disp_Curves')
OUZ_QRZ_per = data[:,1]
OUZ_QRZ_gvel = data[:,0]
plt.plot(OUZ_QRZ_per,OUZ_QRZ_gvel, '--', color=color1, label='OUZ-QRZ')

data = np.genfromtxt('PXZ_WCZ_Lin_Disp_Curves')
PXZ_WCZ_per = data[:,1]
PXZ_WCZ_gvel = data[:,0]
plt.plot(PXZ_WCZ_per,PXZ_WCZ_gvel, '--', color=color2, label='PXZ-WCZ')
# Lots more files will be plotted in the final code
py.grid(True)
plt.legend(loc="lower right",prop={'size':10})
plt.savefig('Test')
plt.show()

【问题讨论】:

标签: python colors matplotlib color-mapping


【解决方案1】:

您可以采取几种不同的方法。在您的初始示例中,您使用不同的颜色专门为每条线着色。如果您能够遍历要绘制的数据/颜色,那效果很好。手动分配每种颜色,就像你现在做的那样,是很多工作,即使是 20 行,但想象一下如果你有 100 或更多。 :)

Matplotlib 还允许您使用自己的颜色编辑默认的“颜色循环”。考虑这个例子:

numlines = 10

data = np.random.randn(150, numlines).cumsum(axis=0)
plt.plot(data)

这给出了默认行为,并导致:

如果您想使用默认的 Matplotlib 颜色图,可以使用它来检索颜色值。

# pick a cmap
cmap = plt.cm.RdYlBu

# get the colors
# if you pass floats to a cmap, the range is from 0 to 1, 
# if you pass integer, the range is from 0 to 255
rgba_colors = cmap(np.linspace(0,1,numlines))

# the colors need to be converted to hexadecimal format
hex_colors = [mpl.colors.rgb2hex(item[:3]) for item in rgba_colors.tolist()]

然后,您可以将颜色列表分配给 Matplotlib 中的 color cycle 设置。

mpl.rcParams['axes.color_cycle'] = hex_colors

在此更改之后制作的任何绘图都将自动循环显示这些颜色:

plt.plot(data)

【讨论】:

  • 嗨 Rutger,我的线路有问题:hex_colors = [mpl.colors.rgb2hex(item[:3]) for item in rgba_colors.tolist()] 我收到一条错误消息 hex_colors = [plt.colors.rgb2hex(item[:3]) for item in rgba_colors.tolist()] AttributeError: 'function' object has no attribute 'rgb2hex' 我不知道如何解决这个问题?
  • 尝试导入 matplotlib,例如:import matplotlib as mpl
猜你喜欢
  • 2020-06-09
  • 2011-07-07
  • 2017-10-21
  • 2021-10-31
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多