2015-06-04 52 views
2

我想在散景的條形圖上劃一條線。我曾嘗試過:散景,酒吧和折線圖的組合

p1 = figure()... 

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

show(p1) 

到目前爲止,我沒有運氣。

回答

6

使用Basic Glyphs可以在Bokeh中的一個圖中組合兩個或更多圖。

對於你的問題,我們可以使用線和矩形。

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) 

的情節,我們得到:

enter image description here

4

捎帶上@tomaskazemekas:雖然它可能是最好避免混合繪圖和圖表的水平內散景,它是可以修改的高級別使用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) 

結果以類似的曲線圖: Bar and Line Plot

+0

'from bokeh.models.glyphs import Line as Line_glyph'爲什麼要使別名長於原來的名稱.... -_- – dopatraman

+2

感謝您的提問。它可以避免與'from bokeh.charts導入行'發生碰撞,該行通常在同一分析中導入其他地塊。還要在代碼中清楚地區分字形對象和圖表對象。 –