Bokeh 1.1反转Y轴的vbar柱状图绘制异常问题
解决Bokeh反向Y轴下柱状图(vbar)方向问题
我懂你遇到的这个头疼问题——把Y轴设为(5,1)实现反向排序后,柱状图的柱子居然从顶部往下伸,完全不是你想要的从底部5.0向上到评分值的效果。这其实是因为Bokeh的vbar默认把bottom=0作为柱子的起始点,但在你的反向Y轴里,0已经超出了(5,1)的范围,所以柱子会从Y轴顶端(也就是1的位置)开始向下画到top指定的评分值。
要搞定这个很简单,只需要给vbar显式设置bottom=5,让柱子从Y轴底部(5.0的位置)向上延伸到你的平均评分值就行。另外还得修正你代码里的一个小笔误:range=p2.x_range应该改成range=fig.x_range,毕竟你定义的figure变量是fig不是p2。
修改后的完整代码如下:
import pandas as pd import numpy as np from bokeh.plotting import figure from bokeh.io import show from bokeh.transform import dodge Years = [2010, 2011, 2010, 2012, 2011, 2013, 2013] ratings_df = pd.DataFrame(Years) ratings_df.columns = ['Years'] ratings_df['Math_Mean_Ratings'] = [1.0, 2.0, 1.5, 3.0, 5.0, 1.0, 2.0] ratings_df['German_Mean_Ratings'] = [3.0, 1.0, 2.0, 3.0, 4.0, 1.5, 2.0] table1 = pd.pivot_table(ratings_df, values=['Math_Mean_Ratings', 'German_Mean_Ratings'], index='Years', aggfunc=np.mean) fig_title = 'Instructor Ratings: 2010 to 2013' fig = figure(plot_width=600, plot_height=300, title=fig_title, y_range=(5,1)) # 设置bottom=5,让柱子从Y轴底部(5.0)向上延伸 fig.vbar(x=dodge('Years', -0.2, range=fig.x_range), width=0.3, bottom=5, # 关键设置 top='Math_Mean_Ratings', source=table1, color='deepskyblue') fig.vbar(x=dodge('Years', 0.2, range=fig.x_range), width=0.3, bottom=5, # 关键设置 top='German_Mean_Ratings', source=table1, color='midnightblue') show(fig)
这个方案完美贴合你用中层绘图接口vbar的需求,不用手动创建矩形,而且完全适配你频繁更新数据的场景。
内容的提问来源于stack exchange,提问作者jfhannon
相关产品推荐
相关产品推荐

