Python Bokeh随机颜色生成器

2024-05-13 10:39:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在这里的第一篇文章。我正在编写Python代码来模拟200天内1000个粒子的随机运动并绘制到Bokeh图上,我想为每个粒子生成一个随机颜色代码。然而,绘图似乎是使用最后一个RGB颜色代码来绘制点。有没有办法让随机颜色发挥作用?谢谢

def color_gen():
co=(round(random.random()*250),round(random.random()*250),round(random.random()*250))
return co

TOOLS="pan,wheel_zoom,reset,poly_select,box_select"


p = figure(plot_width=900, plot_height=900, 
                        x_axis_type='auto',y_axis_type='auto',
                          title='Concentration')

i=1 #Particale ID
c=1 #Days
while i<=imax:
    co=color_gen()
    # print(co)
    while c<=cmax:
        cxname="deltax"+str(c)
        xsumname="XSum"+str(c)
        p.circle(data[xsumname], c, legend_label='Partical {}'.format(c), size=2, color=co)
        c=c+1
    i=i+1

p.legend.click_policy="hide"
p.legend.location = "top_left"

p.xaxis.axis_label = 'Z (m)'
p.yaxis.axis_label = 'C0 (kg/cu.m)'



# show the results
show(p)

enter image description here


Tags: autoplottype绘制粒子randomselectlabel
1条回答
网友
1楼 · 发布于 2024-05-13 10:39:18

首先,像circle这样的Bokeh图示符旨在以矢量化方式使用,即对circle的单个调用可用于绘制1000个圆。事实上,做相反的事情,在一个循环中调用circle1000次以单独绘制1000个单圈,无论是在Python方面,还是在浏览器中,都将是非常无性能的。这根本不是API的用途

根据您的描述,您的代码应类似于:

from bokeh.models import ColumnDataSource

source = ColumnDataSource(data={
    'x'     : [ << 1000 x coordindates    >> ],
    'y'     : [ << 1000 y coordindates    >> ],
    'color' : [ << 1000 random RGB colors >> ],
})

plot = figure(...)
plot.circle('x', 'y', color='color', source=source)

这将用您在数据源中输入的1000种随机颜色绘制1000个圆。还有其他的可能性,但这是最简单的开始。您可以在《用户指南》的Providing Data一章中阅读有关向Bokeh提供数据的更多信息

相关问题 更多 >