I am trying to create a Bar Chart
here, I already have figure
object, but want to assign x_range
later instead of inside figure object
.
I have tried various techniques shown at the end, I am using Bokeh 1.4
def generate_bar_chart(
self, lst_category,lst_frequency, lst_colors, str_xlabel, str_ylabel, str_plot_title,
plot_height=700, plot_width=800, width_bar=0.6):
try:
source = ColumnDataSource(
dict(
x=lst_category,
values=lst_frequency,
color=lst_colors[:len(lst_category)]
)
)
hover_tool = HoverTool(
tooltips=[("Prod Order", "@x"), ("Frequency", "@values")]
)
p = figure(
x_range=lst_category, # I want to set it programatically afterwards, not here
title=str_plot_title,
plot_height=plot_height,
plot_width=plot_width,
background_fill_color="#f9f9f9",
)
p.add_tools(hover_tool)
p.vbar(
x="x",
top="values",
width=width_bar,
source=source,
line_color="#020B13",
)
# p.xgrid.grid_line_color = None
p.y_range.start = 0
p.x_range.range_padding = 0.2
p.xaxis.axis_label = str_xlabel
p.yaxis.axis_label = str_ylabel
p.xaxis.major_label_orientation = 1.1
p.outline_line_color = "#020B13"
p.xaxis.major_label_text_font_size = "11pt"
p.yaxis.major_label_text_font_size = "11pt"
p.yaxis.axis_label_text_font_size = "11pt"
p.xaxis.axis_label_text_font_size = "11pt"
p.yaxis.axis_label_text_font_style = "bold"
p.xaxis.axis_label_text_font_style = "bold"
p.title.text_font_size = "20pt"
show(p)
return True
except Exception as e:
if hasattr(e, "message"):
print(e.message)
else:
print(e)
# I want to do like this
p.x_range = lst_category
# Tried with:
## Not working
p.x_range.factors = lst_category
#
p.x_range=FactorRange(factors=lst_category)
Without a complete minimal reproducer, the best that can be offered is a demonstration of it working on an unrelated, but complete, toy example, which will hopefully be useful as a reference:
from bokeh.io import show
from bokeh.models import ColumnDataSource
from bokeh.models import FactorRange
from bokeh.plotting import figure
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]
source = ColumnDataSource(data=dict(fruits=fruits, counts=counts))
p = figure(plot_height=350, toolbar_location=None, x_range=FactorRange())
p.vbar(x='fruits', top='counts', width=0.9, source=source)
p.xgrid.grid_line_color = None
p.x_range.factors = fruits
p.y_range.start = 0
p.y_range.end = 9
show(p)