Why the histogrames are gray?

Viewed 52

[enter image description here][1][enter image description here][2]Why the histogrames are gray?

I'm trying to construct a vertical bar chart in Bokeh from a pandas dataframe. I'm struggling to get it colored. It comes always gray. The source of the code come from here : (https://anvil.works/blog/plotting-in-bokeh).

Any clue?

import pandas as pd
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, FactorRange, HoverTool
from bokeh.plotting import figure, show
from bokeh.transform import factor_cmap
df1 = pd.read_csv('uk-election-results1.csv', sep=(';'))
output_file("elections.html")
x = [(str(r[1]['year']), r[1]['party']) for r in df1.iterrows()]
y = df1['seats']    # Bokeh wraps your data in its own objects to support interactivity
source = ColumnDataSource(data={'x': x, 'y': y})
cmap = {
    'Conservative':'#0343df',
    'Labour':'#e50000',
    'Liberal':'#ffff14',
    'Others':'#929591'
}
fill_color = factor_cmap('x', palette=list(cmap.values()), factors=list(cmap.keys()), start=1, end=2)
p = figure(x_range=FactorRange(*x), width=2000, title="Election results")
p.vbar(x='x', top='y', width=0.9, source=source, fill_color=fill_color, line_color=fill_color)

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.yaxis.axis_label = 'Seats'
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None

show(p)

CSV file : https://github.com/psagarriga/Test1/blob/main/uk-election-results1.csv

1 Answers

As @bigredot mentioned the factors have to match, I also found a bit confusing the use a tuple in the colormap, so I added an extra column, but the colors are showing up now.

import pandas as pd
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, FactorRange, HoverTool
from bokeh.plotting import figure, show
from bokeh.transform import CategoricalColorMapper

df1 = pd.read_csv('uk-election-results1.csv', sep=(';'))
output_file("elections.html")
x = [(str(r[1]['year']), r[1]['party']) for r in df1.iterrows()]
y = df1['seats']    # Bokeh wraps your data in its own objects to support interactivity
source = ColumnDataSource(data={'x': x, 'y': y, 'p':df1['party']})
cmap = {
    'Conservative':'#0343df',
    'Labour':'#e50000',
    'Liberal':'#ffff14',
    'Others':'#929591'
}
mapper = CategoricalColorMapper(palette=['#0343df', '#e50000', '#ffff14', '#929591'], 
                                    factors=['conservative', 'labour', 'liberal', 'others'])
p = figure(x_range=FactorRange(*x), width=2000, title="Election results")
p.vbar(x='x', top='y', width=0.9, source=source, fill_color={'field':'p', 'transform':mapper}, line_color={'field':'p', 'transform':mapper})

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.yaxis.axis_label = 'Seats'
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None

show(p)
Related