Search code examples
pythonbokehbokehjs

Bokeh Graph Starting or Finishing with NaN Y-Axis Values Is Not Shown


I am trying to get a graph that has all of the x-axis values filled but starts with y-axis values that are NaN. It appears that the graph will start at the first real y-axis value. Here is the example:

from bokeh.plotting import figure, output_file, show

output_file("line.html")
p = figure(plot_width=400, plot_height=400)

# add a line renderer with a NaN
n = float('nan')
p.line(
    [1, 2, 3, 4, 5], # x-axis
    [n, n, 7, 2, 4], # y-axis
    line_width=2
)
show(p)

This is the result: Bokeh graph

As you can see the first 2 elements of the x-axis array aren't shown. I was hoping to find a way to force bokeh graph to show all values or a workaround to the same effect.


Solution

  • You could explicitly set the start (or end) of the plot's x (or y) axis. Like so:

    from bokeh.plotting import figure, output_file, show
    
    output_file("line.html")
    p = figure(plot_width=400, plot_height=400)
    
    # add a line renderer with a NaN
    n = float('nan')
    x_values = [1, 2, 3, 4, 5]  # x-axis
    y_values = [n, n, 7, 2, 4]  # y-axis
    p.line(x=x_values, y=y_values, line_width=2)
    
    # of course in real life it'd make sense to do max and min of x and y,
    # but this is all we need for your specific example.
    p.x_range.start = min(x_values)
    
    show(p)