Continuous error band with Plotly Express in Python [duplicate]

2024/11/16 4:23:43

I need to plot data with continuous error bands. I would like to use Plotly Express in the same way as plotly.express.scatter, but instead of error bars to get continuous error bands. With "continuous error bands" I am talking about this:

enter image description here

Answer

I wrote the following function to extend plotly.express.line with the same high level interface of Plotly Express. In case it is useful to other people, this is the function:

import plotly.express as px
import plotly.graph_objs as godef 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/8849755reordered_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

and this is an usage example:

import plotly.express as px
import pandasdf = 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,color = 'country',title = f'Using error {error_y_mode}',markers = '.',)fig.show()

which should produce the following two plots: enter image description here enter image description here

https://en.xdnf.cn/q/71384.html

Related Q&A

How to preprocess training set for VGG16 fine tuning in Keras?

I have fine tuned the Keras VGG16 model, but Im unsure about the preprocessing during the training phase.I create a train generator as follow:train_datagen = ImageDataGenerator(rescale=1./255) train_ge…

Using Python like PHP in Apache/Windows

I understand that I should use mod_wsgi to run Python, and I have been trying to get that set up, but Im confused about it:This is a sample configuration I found for web.py:LoadModule wsgi_module modul…

django-oauth-toolkit : Customize authenticate response

I am new to Django OAuth Toolkit. I want to customize the authenticate response.My authenticate url configuration on django application is : url(authenticate/,include(oauth2_provider.urls, namespace=oa…

Pushing local branch to remote branch

I created new repository in my Github repository.Using the gitpython library Im able to get this repository. Then I create new branch, add new file, commit and try to push to the new branch.Please chec…

Does Pandas, SciPy, or NumPy provide a cumulative standard deviation function?

I have a Pandas series. I need to get sigma_i, which is the standard deviation of a series up to index i. Is there an existing function which efficiently calculates that? I noticed that there are the …

Python: compile into an Unix commandline app

I am not sure if I searched for the wrong terms, but I could not find much on this subject. I am on osx and Id like to compile a commandline python script into a small commandline app, that I can put i…

ModuleNotFoundError in PySpark Worker on rdd.collect()

I am running an Apache Spark program in python, and I am getting an error that I cant understand and cant begin to debug. I have a driver program that defines a function called hound in a file called h…

Sphinx is not able to import anything

I am trying to use sphinx to document a project of mine. I have used autodoc strings within all of my modules and files. I used sphinx-apidoc to automatically generate rst files for my code. So far, so…

Python : why a method from super class not seen?

i am trying to implement my own version of a DailyLogFile from twisted.python.logfile import DailyLogFileclass NDailyLogFile(DailyLogFile):def __init__(self, name, directory, rotateAfterN = 1, defaultM…

Extract features from last hidden layer Pytorch Resnet18

I am implementing an image classifier using the Oxford Pet dataset with the pre-trained Resnet18 CNN. The dataset consists of 37 categories with ~200 images in each of them. Rather than using the final…