plotly.py: Carpet plot 4 variable axis problem - python

I am trying to use plotly in python to duplicate the 4 variable carpet plot in this link titled "A four-variable carpet plot showing interpolation"
I have noticed two things. First, the length of arrays a and b must be the same. Ok, I can live with that. More importantly, I seem to need to switch the arguments when I call the carpet plot function. I don't understand what I am doing wrong, but if I call
fig = go.Figure(go.Carpet(a=b, b=a, ...
then it work as desired. But why are my a and b vectors reversed...
Here is the entire working example:
import plotly.graph_objects as go
import numpy as np
na = 7
nb = 7
x = np.ndarray(shape=(na, nb))
y = np.ndarray(shape=(na, nb))
a = np.array(range(4,4+na))
b = np.array(range(10,10+nb))
#print(x)
for i in range(0,na):
for j in range(0,nb):
x[i,j] = np.sqrt(a[i] * b[j])
y[i,j] = np.sqrt(b[j])**3 / a[i]
print(a[i], b[j], x[i,j], y[i,j])
print('a=',a)
print('b=',b)
print(x)
fig = go.Figure(go.Carpet(a=b, b=a, x=x, y=y,
aaxis = dict(
tickprefix = 'b=',
ticksuffix = 'm',
smoothing = 1,
minorgridcount = 9,
minorgridwidth = 0.6,
minorgridcolor = 'gray',
gridcolor = 'black',
color = 'blue'
),
baxis = dict(
tickprefix = 'a=',
ticksuffix = 'Pa',
smoothing = 1,
minorgridcount = 9,
minorgridwidth = 0.6,
minorgridcolor = 'gray',
gridcolor = 'black',
color = 'blue'
)
))
fig.show()
Why must I send a=b and b=a?
Why does the code fail if na != nb?
Thanks!

Related

Python don't plot the graph

i have a little problem with matplotlib and python. So my problem is the line don't appear in the plot. I am trying to make a graph of a custom function. My code is here bellow:
fig, ax = plt.subplots(figsize=(8,4))
# Define the x axis values:
x = np.linspace(2000,32000)
# Creating the functions that we will plot
def pmgc(x):
return 0.853
def pmec(x):
return (-124.84/(x)) + pmgc(x)
for x in range(2000,32000):
pmgc(x)
pmec(x)
#Plotting
ax.plot(x,pmgc(x), color = 'blue',linewidth = 3)
ax.plot(x,pmec(x), color = 'red',linewidth = 3)
plt.rcParams["figure.autolayout"] = True
ax.set_xlabel("Renda")
plt.legend(labels = ['Propensão Marginal a Cosumir','Propensão Média a Cosumir'],loc = 'upper left', borderaxespad = 0,bbox_to_anchor=(1.02, 1))
plt.title('Gráfico da Questão 6, item c\nFeito por Luiz Mario. Fonte: Autor', loc='center')
Everytime that i run the code the graph appears without the lines. Please could someone can help me ?
Thank you for the attention :)
A few things. You are defining x as np.linspace(2000,32000) so use another variable in your for loop instead (such as i). Then, you want to create empty lists for your pmgc and pmec values to append to in your for loop. Lastly, you don't want to do for x in range(2000,32000): you want to do for i in np.linspace(2000, 32000): to match the length of your x list. But you've already defined np.linspace(2000, 32000) above in your code when you set x equal to it. So just do for i in x:. Put it all together, and you get your lines:
fig, ax = plt.subplots(figsize=(8,4))
# Define the x axis values:
x = np.linspace(2000,32000)
# Creating the functions that we will plot
def pmgc(x):
return 0.853
def pmec(x):
return (-124.84/(x)) + pmgc(x)
pmgc_list = []
pmec_list = []
for i in x:
pmgc_list.append(pmgc(i))
pmec_list.append(pmec(i))
#Plotting
ax.plot(x,pmgc_list, color = 'blue',linewidth = 3)
ax.plot(x,pmec_list, color = 'red',linewidth = 3)
plt.rcParams["figure.autolayout"] = True
ax.set_xlabel("Renda")
plt.legend(labels = ['Propensão Marginal a Cosumir','Propensão Média a Cosumir'],loc = 'upper left', borderaxespad = 0,bbox_to_anchor=(1.02, 1))
plt.title('Gráfico da Questão 6, item c\nFeito por Luiz Mario. Fonte: Autor', loc='center')
Output:
You can create two lists that contain the info this way
# Define the x axis values:
x = np.linspace(2000,32000)
# Creating the functions that we will plot
# create three empty sets
x_list = []
y_list1 = []
y_list2 = []
def pmgc(x):
return 0.853
def pmec(x):
return (-124.84/(x)) + pmgc(x)
for x in range(2000,32000):
# fill in the sets
x_list.append(x)
y_list1.append(pmgc(x))
y_list2.append(pmec(x))
#Plotting
# add x_list and y_list respectively
ax.plot(x_list,y_list1, color = 'blue',linewidth = 3)
ax.plot(x_list,y_list2, color = 'red',linewidth = 3)
plt.rcParams["figure.autolayout"] = True
ax.set_xlabel("Renda")
plt.legend(labels = ['Propensão Marginal a Cosumir','Propensão Média a Cosumir'],loc = 'upper left', borderaxespad = 0,bbox_to_anchor=(1.02, 1))
plt.title('Gráfico da Questão 6, item c\nFeito por Luiz Mario. Fonte: Autor', loc='center')
plt.show()
this might not be the best way to do it, but it will work.

Plotly - "grouped" scatter plot

Suppose I have the following pandas data frame:
import pandas as pd
d = {'Person': ['Bob']*9 + ['Alice']*9,
'Time': ['Morining']*3 + ['Noon']*3 + ['Evening']*3 + ['Morining']*3 + ['Noon']*3 + ['Evening']*3,
'Color': ['Red','Blue','Green']*6,
'Energy': [1,5,4,7,3,6,8,4,2,9,8,5,2,6,7,3,8,1]}
df = pd.DataFrame(d)
How can I create a plot like this?
(Excuse the crude plotting)
I've tried tricking scatter, strip and box plots into this, but with no success.
Thank you!
generate a scatter trace per Person
a bit of logic on x so that each person is offset. Hence hovertext and xaxis ticks
import plotly.graph_objects as go
xbase = pd.Series(df["Time"].unique()).reset_index().rename(columns={"index":"x",0:"Time"})
dfp = df.merge(xbase, on="Time").set_index("Person")
go.Figure(
[
go.Scatter(
name=p,
x=dfp.loc[p, "x"] + i/10,
y=dfp.loc[p, "Energy"],
text=dfp.loc[p, "Time"],
mode="markers",
marker={"color": dfp.loc[p, "Color"], "symbol":i, "size":10},
hovertemplate="(%{text},%{y})"
)
for i, p in enumerate(dfp.index.get_level_values("Person").unique())
]
).update_layout(xaxis={"tickmode":"array", "tickvals":xbase["x"], "ticktext":xbase["Time"]})
You've already received some great suggestions, but since you're still wondering about:
What if I also want the colors to show in the legend?
I'd just like to chip in that px.scatter comes really close to being an optimal approach right out of the box. The only thing that's missing is jitter. Still, the plot below can be produced by these few lines of code:
fig = px.scatter(df, x = 'Time', y = 'Energy', color = 'Color', symbol = 'Person')
fig.for_each_trace(lambda t: t.update(marker_color = t.name.split(',')[0],
name = t.name.split(',')[1], x = [1,2,3]))
fig.for_each_trace(lambda t: t.update(x=tuple([x + 0.2 for x in list(t.x)])) if t.name == ' Alice' else ())
Complete code:
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
# data
d = {'Person': ['Bob']*9 + ['Alice']*9,
'Time': ['Morining']*3 + ['Noon']*3 + ['Evening']*3 + ['Morning']*3 + ['Noon']*3 + ['Evening']*3,
'Color': ['Red','Blue','Green']*6,
'Energy': [1,5,4,7,3,6,8,4,2,9,8,5,2,6,7,3,8,1]}
df = pd.DataFrame(d)
# figure setup
fig = px.scatter(df, x = 'Time', y = 'Energy', color = 'Color', symbol = 'Person')
# some customizations in order to get to the desired result:
fig.for_each_trace(lambda t: t.update(marker_color = t.name.split(',')[0],
name = t.name.split(',')[1],
x = [1,2,3]))
# jitter
fig.for_each_trace(lambda t: t.update(x=tuple([x + 0.2 for x in list(t.x)])) if t.name == ' Alice' else ())
# layout
fig.update_layout(xaxis={"tickmode":"array","tickvals":[1,2,3],"ticktext":df.Time.unique()})
fig.show()
Room for improvement:
Some elements of the snippet above could undoubtedly be made more dynamic, like x = [1,2,3] which should take into account a varying number of elements on the x-axis. The same goes for the number of people and the arguments used for jitter. But I can look into that too if this is something you can use.
You can go through each row the DataFrame using itertuples (better performance than iterrows), and map 'Morning', 'Noon', and 'Evening' values to 1,2,3, respectively, and then jitter the x-values by mapping 'Bob' to '-0.05' and 'Alice' to 0.05 and adding these values to each of the x-values. You can also pass the 'Color' information to the marker_color argument.
Then map the tickvalues of 1,2,3 back to 'Morning','Noon' and 'Evening' and also use a legendgroup to get only one Bob and one Alice legend marker to display (to stop the marker for each trace from displaying in the legend)
import pandas as pd
import plotly.graph_objects as go
d = {'Person': ['Bob']*9 + ['Alice']*9,
'Time': ['Morning']*3 + ['Noon']*3 + ['Evening']*3 + ['Morning']*3 + ['Noon']*3 + ['Evening']*3,
'Color': ['Red','Blue','Green']*6,
'Energy': [1,5,4,7,3,6,8,4,2,9,8,5,2,6,7,3,8,1]}
df = pd.DataFrame(d)
shapes = {'Bob': 'circle', 'Alice': 'diamond'}
time = {'Morning':1, 'Noon':2, 'Evening':3}
jitter = {'Bob': -0.05, 'Alice': 0.05}
fig = go.Figure()
## position 1 of each row is Person... position 4 is the Energy value
s = df.Person.shift() != df.Person
name_changes = s[s].index.values
for row in df.itertuples():
if row[0] in name_changes:
fig.add_trace(go.Scatter(
x=[time[row[2]] + jitter[row[1]]],
y=[row[4]],
legendgroup=row[1],
name=row[1],
mode='markers',
marker_symbol=shapes[row[1]],
marker_color=row[3],
showlegend=True
))
else:
fig.add_trace(go.Scatter(
x=[time[row[2]] + jitter[row[1]]],
y=[row[4]],
legendgroup=row[1],
name=row[1],
mode='markers',
marker_symbol=shapes[row[1]],
marker_color=row[3],
showlegend=False
))
fig.update_traces(marker=dict(size=12,line=dict(width=2,color='DarkSlateGrey')))
fig.update_layout(
xaxis=dict(
tickmode='array',
tickvals=list(time.values()),
ticktext=list(time.keys())
)
)
fig.show()
In case you only want to go with matplotlib and don't want any extra dependencies, here is a sample code. (Pandas operations groupbys etc are left for you to optimize)
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
from matplotlib.lines import Line2D
df = pd.DataFrame(
{
'Person': ['Bob'] * 9 + ['Alice'] * 9,
'Time': ['Morning'] * 3
+ ['Noon'] * 3
+ ['Evening'] * 3
+ ['Morning'] * 3
+ ['Noon'] * 3
+ ['Evening'] * 3,
'Color': ['Red', 'Blue', 'Green'] * 6,
'Energy': [1, 5, 4, 7, 3, 6, 8, 4, 2, 9, 8, 5, 2, 6, 7, 3, 8, 1],
}
)
plt.figure()
x = ['Morning', 'Noon', 'Evening']
# Transform function
offset = lambda p: transforms.ScaledTranslation(
p / 72.0, 0, plt.gcf().dpi_scale_trans
)
trans = plt.gca().transData
# Use this to center transformation
start_offset = -len(df['Person'].unique()) // 2
# Define as many markers as people you have
markers = ['o', '^']
# Use this for custom legend
custom_legend = []
# Do this if you need to aggregate
df = df.groupby(['Person', 'Time', 'Color'])['Energy'].sum().reset_index()
df = df.set_index('Time')
for i, [person, pgroup] in enumerate(df.groupby('Person')):
pts = (i + start_offset) * 10
marker = markers[i]
transform = trans + offset(pts)
# This is for legend, not plotted
custom_legend.append(
Line2D(
[0],
[0],
color='w',
markerfacecolor='black',
marker=marker,
markersize=10,
label=person,
)
)
for color, cgroup in pgroup.groupby('Color'):
mornings = cgroup.loc[cgroup.index == 'Morning', 'Energy'].values[0]
noons = cgroup.loc[cgroup.index == 'Noon', 'Energy'].values[0]
evenings = cgroup.loc[cgroup.index == 'Evening', 'Energy'].values[0]
# This stupid if is because you need to define at least one non
# transformation scatter be it first or whatever.
if pts == 0:
plt.scatter(
x,
[mornings, noons, evenings],
c=color.lower(),
s=25,
marker=marker,
)
else:
plt.scatter(
x,
[mornings, noons, evenings],
c=color.lower(),
s=25,
marker=marker,
transform=transform,
)
plt.ylabel('Energy')
plt.xlabel('Time')
plt.legend(handles=custom_legend)
plt.margins(x=0.5)
plt.show()

how to plot a range with a line in the center with Plotly, in Python [duplicate]

How can I use Plotly to produce a line plot with a shaded standard deviation? I am trying to achieve something similar to seaborn.tsplot. Any help is appreciated.
The following approach is fully flexible with regards to the number of columns in a pandas dataframe and uses the default color cycle of plotly. If the number of lines exceed the number of colors, the colors will be re-used from the start. As of now px.colors.qualitative.Plotly can be replaced with any hex color sequence that you can find using px.colors.qualitative:
Alphabet = ['#AA0DFE', '#3283FE', '#85660D', '#782AB6', '#565656', '#1...
Alphabet_r = ['#FA0087', '#FBE426', '#B00068', '#FC1CBF', '#C075A6', '...
[...]
Complete code:
# imports
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import numpy as np
# sample data in a pandas dataframe
np.random.seed(1)
df=pd.DataFrame(dict(A=np.random.uniform(low=-1, high=2, size=25).tolist(),
B=np.random.uniform(low=-4, high=3, size=25).tolist(),
C=np.random.uniform(low=-1, high=3, size=25).tolist(),
))
df = df.cumsum()
# define colors as a list
colors = px.colors.qualitative.Plotly
# convert plotly hex colors to rgba to enable transparency adjustments
def hex_rgba(hex, transparency):
col_hex = hex.lstrip('#')
col_rgb = list(int(col_hex[i:i+2], 16) for i in (0, 2, 4))
col_rgb.extend([transparency])
areacol = tuple(col_rgb)
return areacol
rgba = [hex_rgba(c, transparency=0.2) for c in colors]
colCycle = ['rgba'+str(elem) for elem in rgba]
# Make sure the colors run in cycles if there are more lines than colors
def next_col(cols):
while True:
for col in cols:
yield col
line_color=next_col(cols=colCycle)
# plotly figure
fig = go.Figure()
# add line and shaded area for each series and standards deviation
for i, col in enumerate(df):
new_col = next(line_color)
x = list(df.index.values+1)
y1 = df[col]
y1_upper = [(y + np.std(df[col])) for y in df[col]]
y1_lower = [(y - np.std(df[col])) for y in df[col]]
y1_lower = y1_lower[::-1]
# standard deviation area
fig.add_traces(go.Scatter(x=x+x[::-1],
y=y1_upper+y1_lower,
fill='tozerox',
fillcolor=new_col,
line=dict(color='rgba(255,255,255,0)'),
showlegend=False,
name=col))
# line trace
fig.add_traces(go.Scatter(x=x,
y=y1,
line=dict(color=new_col, width=2.5),
mode='lines',
name=col)
)
# set x-axis
fig.update_layout(xaxis=dict(range=[1,len(df)]))
fig.show()
I was able to come up with something similar. I post the code here to be used by someone else or for any suggestions for improvements.
import matplotlib
import random
import plotly.graph_objects as go
import numpy as np
#random color generation in plotly
hex_colors_dic = {}
rgb_colors_dic = {}
hex_colors_only = []
for name, hex in matplotlib.colors.cnames.items():
hex_colors_only.append(hex)
hex_colors_dic[name] = hex
rgb_colors_dic[name] = matplotlib.colors.to_rgb(hex)
data = [[1, 3, 5, 4],
[2, 3, 5, 4],
[1, 1, 4, 5],
[2, 3, 5, 4]]
#calculating mean and standard deviation
mean=np.mean(data,axis=0)
std=np.std(data,axis=0)
#draw figure
fig = go.Figure()
c = random.choice(hex_colors_only)
fig.add_trace(go.Scatter(x=np.arange(4), y=mean+std,
mode='lines',
line=dict(color=c,width =0.1),
name='upper bound'))
fig.add_trace(go.Scatter(x=np.arange(4), y=mean,
mode='lines',
line=dict(color=c),
fill='tonexty',
name='mean'))
fig.add_trace(go.Scatter(x=np.arange(4), y=mean-std,
mode='lines',
line=dict(color=c, width =0.1),
fill='tonexty',
name='lower bound'))
fig.show()
Great custom responses posted by others. In case someone is interested in code from the official plotly website, see here: https://plotly.com/python/continuous-error-bars/
I wrote a function to extend plotly.express.line with the same high level interface of Plotly Express. The line function (source code below) is used in the same exact way as plotly.express.line but allows for continuous error bands with the flag argument error_y_mode which can be either 'band' or 'bar'. In the second case it produces the same result as the original plotly.express.line. Here is an usage example:
import plotly.express as px
df = px.data.gapminder().query('continent=="Americas"')
df = df[df['country'].isin({'Argentina','Brazil','Colombia'})]
df['lifeExp std'] = df['lifeExp']*.1 # Invent some error data...
for error_y_mode in {'band', 'bar'}:
fig = line(
data_frame = df,
x = 'year',
y = 'lifeExp',
error_y = 'lifeExp std',
error_y_mode = error_y_mode, # Here you say `band` or `bar`.
color = 'country',
title = f'Using error {error_y_mode}',
markers = '.',
)
fig.show()
which produces the following two plots:
The source code of the line function that extends plotly.express.line is this:
import plotly.express as px
import plotly.graph_objs as go
def line(error_y_mode=None, **kwargs):
"""Extension of `plotly.express.line` to use error bands."""
ERROR_MODES = {'bar','band','bars','bands',None}
if error_y_mode not in ERROR_MODES:
raise ValueError(f"'error_y_mode' must be one of {ERROR_MODES}, received {repr(error_y_mode)}.")
if error_y_mode in {'bar','bars',None}:
fig = px.line(**kwargs)
elif error_y_mode in {'band','bands'}:
if 'error_y' not in kwargs:
raise ValueError(f"If you provide argument 'error_y_mode' you must also provide 'error_y'.")
figure_with_error_bars = px.line(**kwargs)
fig = px.line(**{arg: val for arg,val in kwargs.items() if arg != 'error_y'})
for data in figure_with_error_bars.data:
x = list(data['x'])
y_upper = list(data['y'] + data['error_y']['array'])
y_lower = list(data['y'] - data['error_y']['array'] if data['error_y']['arrayminus'] is None else data['y'] - data['error_y']['arrayminus'])
color = f"rgba({tuple(int(data['line']['color'].lstrip('#')[i:i+2], 16) for i in (0, 2, 4))},.3)".replace('((','(').replace('),',',').replace(' ','')
fig.add_trace(
go.Scatter(
x = x+x[::-1],
y = y_upper+y_lower[::-1],
fill = 'toself',
fillcolor = color,
line = dict(
color = 'rgba(255,255,255,0)'
),
hoverinfo = "skip",
showlegend = False,
legendgroup = data['legendgroup'],
xaxis = data['xaxis'],
yaxis = data['yaxis'],
)
)
# Reorder data as said here: https://stackoverflow.com/a/66854398/8849755
reordered_data = []
for i in range(int(len(fig.data)/2)):
reordered_data.append(fig.data[i+int(len(fig.data)/2)])
reordered_data.append(fig.data[i])
fig.data = tuple(reordered_data)
return fig

tickformat in Plotly Python

I am trying to format my Plotly Bar Chart x-axis to percentages with 3 decimal points.
import chart_studio.plotly as py #for plotting
import plotly.graph_objs as go
y = ['niner', 'deuce', 'checker']
x = [0.03, -0.05, 0.075]
fig = go.Figure(go.Bar(y = y, x = x,
name = 'returns',
orientation = 'h',
marker = dict(color = '#003663',
line = dict(
color = '#afafaf',
width = 1.5)
)))
fig.update_layout(
title = 'Why So Hard Plotly?',
xaxis = dict(
tickformat = '%.format.%3f',
title = 'Returns',
fixedrange = True,
hoverformat = '.3f',
showgrid = True),
yaxis = dict(
fixedrange = True,
hoverformat = '.3f',
showgrid = True,
),
bargap = 0.2,
barmode = 'relative',
)
fig.update_yaxes(automargin=True)
fig.show()
I can get the y-axis to appear as a rounded percentage using tickformat = '%',
but I can't get more decimals to appears. The Plotly d3 documentation isn't clear (to me) how to do this. Any help is appreciated.
Thanks in advance.
I believe that setting tickformat to ".3%" should do it. Formatting 0.512345 this way yields 51.235%.

Logarithmic color scale in plotly

I'm trying to visualize the data with some outliers using Plotly and Python3. Outliers cause the color scale legend to look badly: there are only few high data points, but the legend looks bad: space between 2k and 10k is too big.
So the question is, how to change the appearance of 'color legend' on the right (see image below), so it will show the difference between 0 to 2k mostly? Unfortunately, couldn't get an answer from this doc file
Sample code (jupyter notebook):
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()
x = np.random.randn(100,1) + 3
y = np.random.randn(100,1) + 10
x = np.reshape(x, 100)
y = np.reshape(y, 100)
color = np.random.randint(0,1000, [100])
color[[1,3,5]] = color[[1,3,5]] + 10000 # create outliers in color var
trace = Scatter(
x = x,
y = y,
mode = 'markers',
marker=dict(
color = color,
showscale=True,
colorscale = [[0, 'rgb(166,206,227, 0.5)'],
[0.05, 'rgb(31,120,180,0.5)'],
[0.1, 'rgb(178,223,138,0.5)'],
[0.15, 'rgb(51,160,44,0.5)'],
[0.2, 'rgb(251,154,153,0.5)'],
[1, 'rgb(227,26,28,0.5)']
]
)
)
fig = Figure(data=[trace])
iplot(fig)
What i'm looking for:
You can accomplish what I think you're after by customizing the colorscale, cmin, and cmax properties to have a discrete color change at exactly 2000. Then you can customize colorbar.tickvals to label the boundary as 2000. See https://plot.ly/python/reference/#scatter-marker-colorbar.
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()
x = np.random.randn(100,1) + 3
y = np.random.randn(100,1) + 10
x = np.reshape(x, 100)
y = np.reshape(y, 100)
color = np.random.randint(0,1000, [100])
color[[1,3,5]] = color[[1,3,5]] + 10000 # create outliers in color var
bar_max = 2000
factor = 0.9 # Normalized location where continuous colorscale should end
trace = Scatter(
x = x,
y = y,
mode = 'markers',
marker=dict(
color = color,
showscale=True,
cmin=0,
cmax= bar_max/factor,
colorscale = [[0, 'rgb(166,206,227, 0.5)'],
[0.05, 'rgb(31,120,180,0.5)'],
[0.2, 'rgb(178,223,138,0.5)'],
[0.5, 'rgb(51,160,44,0.5)'],
[factor, 'rgb(251,154,153,0.5)'],
[factor, 'rgb(227,26,28,0.5)'],
[1, 'rgb(227,26,28,0.5)']
],
colorbar=dict(
tickvals = [0, 500, 1000, 1500, 2000],
ticks='outside'
)
)
)
fig = Figure(data=[trace])
iplot(fig)
New figure result
Since you asked with a precise question, I try to reply with a precise answer, even if I don't think this could not be the best in data visualization. Later I show you why.
Anyway, you can normalize the values of the colors and "squeeze" your data in a much smaller interval. It mathematically represents the power to which the number e must be raised to produce the original value. You can use log10 if you're more comfortable with.
The code is very very simple, I attach only the trace definition as the rest is unchanged. I placed a standard cmap for convenience as the interval of the values is continuous.
trace = Scatter(
x = x,
y = y,
mode = 'markers',
marker=dict(
color = np.log(color),
showscale=True,
colorscale = 'RdBu'
)
)
As I said, transforming the values with log isn't always the best. It actually forces the observer to a rough reading of the graph. As example, nevertheless in my example the orange markers range between 410 and 950, can you tell the difference?

Categories