How do you add error bars to Bokeh plots in python?

一世执手 提交于 2019-12-09 02:36:38

问题


I have successfully plotted several data sets and fitted functions using Bokeh however I really need to add error bars to the graphs, how might I go about doing this?


回答1:


EDIT: This is now built into Bokeh, see the documentation:

https://docs.bokeh.org/en/latest/docs/user_guide/annotations.html#whiskers

and

https://docs.bokeh.org/en/latest/docs/user_guide/annotations.html#bands

See https://stackoverflow.com/a/46517148/3406693 for a complete example.


Maybe its a little late but I wanted to do this today too.

It's a shame that bokeh does not offer this function by itself.

import numpy as np
from bokeh.plotting import figure, show, output_file

# some pseudo data
xs = np.linspace(0, 2*np.pi, 25)
yerrs = np.random.uniform(0.1, 0.3, xs.shape)
ys = np.sin(xs) + np.random.normal(0, yerrs, xs.shape)

output_file('bokeh_errorbars.html')

# plot the points
p = figure(title='errorbars with bokeh', width=800, height=400)

p.xaxis.axis_label = 'x'
p.yaxis.axis_label = 'y'


p.circle(xs, ys, color='red', size=5, line_alpha=0)


# create the coordinates for the errorbars
err_xs = []
err_ys = []

for x, y, yerr in zip(xs, ys, yerrs):
    err_xs.append((x, x))
    err_ys.append((y - yerr, y + yerr))

# plot them
p.multi_line(err_xs, err_ys, color='red')

show(p)

And this is the result:

One might want to use it as a function like this:

def errorbar(fig, x, y, xerr=None, yerr=None, color='red', 
             point_kwargs={}, error_kwargs={}):

  fig.circle(x, y, color=color, **point_kwargs)

  if xerr:
      x_err_x = []
      x_err_y = []
      for px, py, err in zip(x, y, xerr):
          x_err_x.append((px - err, px + err))
          x_err_y.append((py, py))
      fig.multi_line(x_err_x, x_err_y, color=color, **error_kwargs)

  if yerr:
      y_err_x = []
      y_err_y = []
      for px, py, err in zip(x, y, yerr):
          y_err_x.append((px, px))
          y_err_y.append((py - err, py + err))
      fig.multi_line(y_err_x, y_err_y, color=color, **error_kwargs)


来源:https://stackoverflow.com/questions/29166353/how-do-you-add-error-bars-to-bokeh-plots-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!