【发布时间】:2019-02-04 09:28:59
【问题描述】:
我在将颜色条添加到对应于幂律的多行图中时遇到问题。
为了为非图像图创建颜色条,我添加了一个虚拟图(来自此处的答案:Matplotlib - add colorbar to a sequence of line plots)。
到颜色条的刻度不对应于绘图的颜色。
我已尝试更改颜色条的规范,并且可以对其进行微调以使其在特定情况下保持准确,但通常我不能这样做。
def plot_loglog_gauss():
from matplotlib import cm as color_map
import matplotlib as mpl
"""Creating the data"""
time_vector = [0, 1, 2, 4, 8, 16, 32, 64, 128, 256]
amplitudes = [t ** 2 * np.exp(-t * np.power(np.linspace(-0.5, 0.5, 100), 2)) for t in time_vector]
"""Getting the non-zero minimum of the data"""
data = np.concatenate(amplitudes).ravel()
data_min = np.min(data[np.nonzero(data)])
"""Creating K-space data"""
k_vector = np.linspace(0,1,100)
"""Plotting"""
number_of_plots = len(time_vector)
color_map_name = 'jet'
my_map = color_map.get_cmap(color_map_name)
colors = my_map(np.linspace(0, 1, number_of_plots, endpoint=True))
# plt.figure()
# dummy_plot = plt.contourf([[0, 0], [0, 0]], time_vector, cmap=my_map)
# plt.clf()
norm = mpl.colors.Normalize(vmin=time_vector[0], vmax=time_vector[-1])
cmap = mpl.cm.ScalarMappable(norm=norm, cmap=color_map_name)
cmap.set_array([])
for i in range(number_of_plots):
plt.plot(k_vector, amplitudes[i], color=colors[i], label=time_vector[i])
c = np.arange(1, number_of_plots + 1)
plt.xlabel('Frequency')
plt.ylabel('Amplitude')
plt.yscale('symlog', linthreshy=data_min)
plt.xscale('log')
plt.legend(loc=3)
ticks = time_vector
plt.colorbar(cmap, ticks=ticks, shrink=1.0, fraction=0.1, pad=0)
plt.show()
通过与图例进行比较,您会发现刻度值与实际颜色不匹配。例如,128 在颜色图中显示为绿色,而在图例中显示为红色。
实际结果应该是一个线性颜色的颜色条。在颜色条上以规则的间隔带有刻度(对应于不规则的时间间隔......)。当然,正确的颜色是刻度值。
(最终该图包含许多图(len(time_vector) ~ 100),我降低了图的数量来说明并能够显示图例。)
澄清一下,这就是我想要的结果。
【问题讨论】:
-
小修正 - 1,2,4,8,16,32,64 ,128,256
-
是的。更新了代码和图片。
-
链接问题中接受的答案没有用。你考虑过其他答案吗?
-
@ImportanceOfBeingErnest:当您撰写此评论时,我正在准备解决方案。确实,我正要说同样的话
-
是的,我尝试了所有这些答案,但无法让它们中的任何一个起作用。
标签: python matplotlib colormap