选择 Bokeh 条形图中条的顺序

7

作为尝试学习使用Bokeh的一部分,我正在尝试制作一个简单的条形图。我按照一定顺序(每周的日子)传递标签,但是Bokeh似乎在按字母顺序进行排序。我该如何使条形图按照原始列表中的顺序显示?

from bokeh.plotting import show
from bokeh.io import output_notebook
from bokeh.charts import Bar
from collections import OrderedDict
import calendar 

output_notebook()

data = OrderedDict()
data['values'] = [2,3,4,5,6,7,8] #values only ascending to make correct graph clear
data['days'] = [calendar.day_name[i-1] for i in range(7)]
p = Bar(data, label='days', values='values', 
         title='OrderedDict Input',xlabel="Day", ylabel="Value")
show(p)

生成的输出

该链接指向生成的输出结果。
4个回答

7

Bokeh项目维护者的注意事项:此答案涉及一种已过时且不建议在任何新代码中使用的API。有关使用现代和完全支持的Bokeh API创建条形图的信息,请参见其他响应。


以下是使用Charts接口保留您示例中标签的原始顺序的方法,已测试Bokeh 0.11.1。

from bokeh.plotting import show
from bokeh.io import output_notebook
from bokeh.charts import Bar
from collections import OrderedDict
import calendar 
from bokeh.charts.attributes import CatAttr

output_notebook()

data = OrderedDict()
data['values'] = [2,3,4,5,6,7,8] #values only ascending to make correct graph clear
data['days'] = [calendar.day_name[i-1] for i in range(7)]
p = Bar(data, label=CatAttr(columns=['days'], sort=False), 
        values='values',title='OrderedDict Input',xlabel="Day", ylabel="Value")
show(p)

2
一般来说,使用任何图表都应该能够明确地指定x(或y)范围。tk的答案非常有帮助,如果您想完全忽略Bar图表类(出于某些原因,这并不是世界上最糟糕的想法)。user666的答案很有帮助,如果您的数据列已经按您想要的顺序排序。否则,您可以自己指定顺序:

星期从周日开始:

from bokeh.models import FactorRange
...
p.x_range = FactorRange(factors=data['days'])

星期天开始

星期一开始:

p.x_range = FactorRange(factors=data['days'][1:] + [data['days'][0]])

enter image description here


2

我不太喜欢像条形图这样的高级图表。它们的定制性不是很强。 手动构建它们通常更容易,而且时间也不会太长。以下是我的建议:

from bokeh.plotting import figure
from bokeh.io import output_file, show
import calendar

values = [2,3,4,5,6,7,8]
days = [calendar.day_name[i-1] for i in range(1,8)]

p = figure(x_range=days)
p.vbar(x=days, width=0.5, top=values, color = "#ff1200")

output_file('foo.html')
show(p)

这将产生:

在此输入图片描述


现在使用vbar更加简单(同时bokeh.charts已被弃用和移除)。许多条形图示例现在位于:https://bokeh.pydata.org/en/latest/docs/user_guide/categorical.html - bigreddot

0

这是与user666的答案相关的评论(我没有足够的积分添加评论)。

我认为在这里使用OrderedDict并没有帮助,因为它只记住了插入键的顺序(即“values”在“days”之前),而不是与这些键关联的值序列的顺序。

另外,FYI,在bokeh GitHub网站上有关于这个问题的讨论,链接在这里:https://github.com/bokeh/bokeh/issues/2924和这里:https://github.com/bokeh/bokeh/pull/3623


1
刚刚意识到OrderedDict已经在原始帖子中了。抱歉。 - JHD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接