ValueError: expected an element of either Enum('solid', 'dashed', 'dotted', 'dotdash', 'dashdot')

ValueError: expected an element of either Enum('solid', 'dashed', 'dotted', 'dotdash', 'dashdot')

我正在尝试输出一个折线图,其中的破折号由数据驱动。我的例子是:

from bokeh.plotting import figure, output_notebook, show
output_notebook()

x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
z = ['dashed', 'dashed', 'dashed', 'solid', 'solid']

p = figure(plot_width=400, plot_height=400)

p.line(x, y, line_width=2, line_dash=z)

show(p)

但是,这会导致:

ValueError: expected an element of either Enum('solid', 'dashed', 'dotted', 'dotdash', 'dashdot'), Regex('^(\d+(\s+\d+)*)?$') or Seq(Int), got ['dashed', 'dashed', 'dashed', 'solid', 'solid']

是否可以根据我的数据集设置线型?

无法使用线条字形列表设置线条破折号。

一些可以帮助您解决问题的事情。尝试使用 MultiLine 字形来绘制图表,并使用 ColumnDataSource 来构建数据。使用 MultiLine 字形可以设置一些线属性以针对多线的每一段进行更改。 line_color 可以通过这种方式更改每个段,但不幸的是 line_dash 属性 不能。

您可以尝试在 Bokeh's Github 上打开一个问题,以允许 MultiLine 字形中的 line_dash 属性 从 ColumnDataSource 设置。

这是一个解决方案的示例。

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from bokeh.models.glyphs import MultiLine

source = ColumnDataSource(data=dict(z=['dashed', 'dashed', 'solid', 'solid'],
                                    xs=[[1, 2], [2, 3], [3, 4], [4, 5]],
                                    ys=[[6, 7], [7, 2], [2, 4], [4, 5]],
                                    color=['green', 'red', 'green', 'green']))

p = figure(plot_width=400, plot_height=400)

glyph = MultiLine(xs='xs', ys='ys', line_color = 'color', line_dash='z', line_width=2)
p.add_glyph(source, glyph)

show(p)

上面代码中可以使用ColumnDataSource设置颜色,这样可以用来区分段,但是line_dash属性还是会报错。