Python Bokeh xy scatter plot and color mapping using palette

65 Views Asked by At

I have three list and I want plot a xy scatter plot in bokeh but color of plot points would depend on value of Y but scaled to value specfied in list 'z'. Note here that 'z' is of different size from x and y

How could I do it?

`  x = list(range(1, 51)) # Data points
  y = random.sample(range(0, 100), 50) # Temperature observed
  z = list(range(0, 100)) color bar temp range.

  source = ColumnDataSource('.....????..........')
  cmap = linear_cmap(field_name='?', palette="Spectral6", low=?, high=?)

  r = p.scatter(y, y, color=cmap, size=15, source=source)`

I tried following the example given on "https://docs.bokeh.org/en/latest/docs/examples/basic/data/linear_cmap_colorbar.html" but did not have any success.

2

There are 2 best solutions below

1
Nina On

Lots going on here that needs attention to get the most out of Bokeh.

1. Data Preparation

Since your 'z' values (representing the scaling factor) have a different range than 'y' (temperature), you need to normalize them. A common approach is min-max normalization:

import numpy as np

def normalize(data, min_val=0, max_val=1):
    return (data - min(data)) / (max(data) - min(data)) * (max_val - min_val) + min_val

z_normalized = normalize(z) 

2. Create a ColumnDataSource

You will need the normalized 'z' values in your data source for the color mapping.

from bokeh.models import ColumnDataSource

source = ColumnDataSource(dict(
    x=x,
    y=y,
    temperature=y,  # Use 'y' for the color field
    z=z_normalized
))

3. Linear Color Mapper

Set the field_name to the column in your data source containing the values that will drive the color mapping (in this case, 'temperature'). You might want to scale the low and high values of the color mapper if there are outliers in your data, ensuring good visual representation.

from bokeh.models import LinearColorMapper

cmap = LinearColorMapper(field_name='temperature', palette="Spectral6", 
                         low=min(y), high=max(y))  

4. Plot and Apply Color Mapping

from bokeh.plotting import figure, show 

p = figure(title="Temperature Plot with Color Scaling")
p.scatter('x', 'y', size=15, source=source,
          color={'field': 'temperature', 'transform': cmap})

Like I said a bit going on there and I won't be able to hand-hold it all the way, but understanding these bigger moves on the structure and intent will help you get the last few.

1
Rajesh Patel On
x = Combined_Data_Air[X1]
y = Combined_Data_Air[Y1a]
z = Combined_Data_Air['xxxxxxx']

source = ColumnDataSource(data = dict( x = x,y=y,z = z))
cmap = linear_cmap(field_name='z', palette="Turbo256",low = 500, high = 2000)
s1.circle(x= 'x', y ='y', source=source,color=cmap, legend_label=Y1a,size=2)

X1 and Y1a are Pandas column names. Above is code which worked for me. Thanks for all the help from members.