Bokeh, combination of bar and line chart

徘徊边缘 提交于 2019-12-11 02:57:24

问题


I am trying to plot a line on top of a bar chart within bokeh. I have tried:

p1 = figure()...

p1.renderer.append(Bar(...))
p1.renderer.append(Line(...))

show(p1)

So far I had no luck.


回答1:


Combination of two or more graphs in one plot in Bokeh is possible using the Basic Glyphs.

For your question we can use line and rect.

from bokeh.plotting import figure, output_file, show
from bokeh.models.ranges import Range1d
import numpy


output_file("line_bar.html")

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

# add a line renderer
p.line([1, 2, 3, 4, 5], [6, 7, 6, 4, 5], line_width=2)

# setting bar values
h = numpy.array([2, 8, 5, 10, 7])

# Correcting the bottom position of the bars to be on the 0 line.
adj_h = h/2

# add bar renderer
p.rect(x=[1, 2, 3, 4, 5], y=adj_h, width=0.4, height=h, color="#CAB2D6")

# Setting the y  axis range   
p.y_range = Range1d(0, 12)

p.title = "Line and Bar"

show(p)

And the plot we get:




回答2:


Piggybacking on @tomaskazemekas: While it's probably best to avoid mixing plotting and chart levels within Bokeh, it is possible to modify a high-level chart object using add_glyph:

from bokeh.charts import Bar, output_file, show
from bokeh.models.ranges import Range1d

from bokeh.models import ColumnDataSource
from bokeh.models.glyphs import Line as Line_glyph

import numpy as np

# create dummy data
df = dict(
    x=[1, 2, 3, 4, 5],
    y=[6, 7, 6, 4, 5],
    h=[2, 8, 5, 10, 7]
)

# create high-level bar chart
p = Bar(data=df, label='x', values='h', color='dodgerblue', title="Bar and Line Plot",
        legend=False, plot_width=400, plot_height=400)

# create source data object from data
source = ColumnDataSource(data=df)

# create a line glyph object which references columns from source data
glyph = Line_glyph(x='x', y='y', line_color='grey', line_width=2)

# add the glyph to the chart
p.add_glyph(source, glyph)

# Setting the y  axis range   
p.y_range = Range1d(0, 12)

output_file("line_bar.html")

show(p)

Results in a similar plot: Bar and Line Plot



来源:https://stackoverflow.com/questions/30643681/bokeh-combination-of-bar-and-line-chart

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