我有一段代码使用matplotlib绘制一组线条,并使用颜色贴图将颜色应用于这些线条。代码摘录和结果如下:
cm = plt.cm.get_cmap('jet')
step = 15
xi = np.linspace(data[data.columns[0]].min(), data[data.columns[0]].max(), 2)
colors_l = np.linspace(0.1, 1, len(state_means[::step]))
for i, beta in enumerate(state_means[::step]):
plt.plot(xi, beta[0] * xi + beta[1], alpha=.2, lw=1, c=cm(colors_l[i]))
此处代码的相关部分是
c=cm(colors_l[i])
位于plt.plot()函数中。这里可以使用参数(在这种情况下为i)索引颜色映射。
但是,如果我尝试使用散景,使用其ColorMapper和line()字形来完成类似的事情,我会遇到并错误。相关的代码行和输出是
call_color_mapper = LinearColorMapper(palette="Viridis256", low=min(call_strike_vals), high=max(call_strike_vals))
call_lines=dict()
call_chain_plot = figure(y_axis_label='Call OI', x_axis_label='Dates', x_axis_type = 'datetime')
for strike in call_strikes:
call_lines[strike] = call_chain_plot.line('TIMESTAMP', strike, line_color=call_color_mapper(int(strike[2:])), source=callSource)
TypeError: 'LinearColorMapper' object is not callable
有没有办法在散景中使用彩色贴图为一组线条字形着色?
答案 0 :(得分:2)
LinearColorMapper
不会在Python中计算颜色。相反,LinearColorMapper
表示在浏览器中以在中发生的颜色映射。如果你真的需要Python中的颜色,你必须手动映射它们,有很多方法可以做到这一点。
但你可能没有,所以在Bokeh中做到这一点的最好方法是使用multi_line
而不是重复调用line
。这部分出于性能原因,Bokeh经过优化,可以在“矢量化”操作中表现最佳。而且,它允许您使用linear_cmap
便利功能为您喜欢的任何数据列制作颜色映射器。这是一个完整的例子:
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.transform import linear_cmap
output_file("cmap.html")
p = figure()
source = ColumnDataSource(data=dict(
xs=[[0,1] for i in range(256)], # x coords for each line (list of lists)
ys=[[i, i+10] for i in range(256)], # y coords for each line (list of lists)
foo=list(range(256)) # data to use for colormapping
))
p.multi_line('xs', 'ys', source=source,
color=linear_cmap('foo', "Viridis256", 0, 255))
show(p)
答案 1 :(得分:0)
虽然@ bigreddot的解决方案确实为line()字形提供了一个很好的替代方案,可以使用linear_cmap()绘制一组行,但它没有提供捕获各行的句柄的方法需要手柄进行进一步处理(例如,为其中一些绘制辅助y轴)。这就是我在OP中收集字典中每行的句柄的原因。
嗯,另一种在循环列表时一次绘制一行的方法如下
from bokeh.palettes import viridis #here viridis is a function that takes\
#parameter n and provides a palette with n equally(almost) spaced colors.
call_colors = viridis(len(call_strikes))
color_key_value_pairs = list(zip(call_strikes, call_colors))
color_dict = dict(color_key_value_pairs)
现在,字典color_dict可用于根据字典中的值访问颜色。所以,我运行OP的代码如下:
call_lines=dict()
for index, strike in enumerate(call_strikes):
call_lines[strike] = call_chain_plot.line('xs', strike, color=color_dict[strike], source=callSource)
我想这就是@ bigreddot在写作时的意思,'如果你真的需要Python中的颜色,你必须手工绘制它们,有很多方法可以做到这一点'。