How to set a fill color between two vertical lines

2024/10/3 4:30:52

Using matplotlib, we can "trivially" fill the area between two vertical lines using fill_between() as in the example:

https://matplotlib.org/3.2.1/gallery/lines_bars_and_markers/fill_between_demo.html#selectively-marking-horizontal-regions-across-the-whole-axes

Using matplotlib, I can make what I need:

enter image description here

We have two signals, and I''m computing the rolling/moving Pearson's and Spearman's correlation. When the correlations go either below -0.5 or above 0.5, I want to shade the period (blue for Pearson's and orange for Spearman's). I also darken the weekends in gray in all plots.

However, I'm finding a hard time to accomplish the same using Plotly. And it will also be helpful to know how to do it between two horizontal lines.

Note that I'm using Plotly and Dash to speed up the visualization of several plots. Users asked for a more "dynamic type of thing." However, I'm not a GUI guy and cannot spend time on this, although I need to feed them with initial results.

BTW, I tried Bokeh in the past, and I gave up for some reason I cannot remember. Plotly looks good since I can use either from Python or R, which are my main development tools.

Thanks,

Carlos

Answer

I don't think there is any built-in Plotly method that that is equivalent to matplotlib's fill_between() method. However you can draw shapes so a possible workaround is to draw a grey rectangle and set the the parameter layer="below" so that the signal is still visible. You can also set the coordinates of the rectangle outside of your axis range to ensure the rectangle extends to the edges of the plot.

You can fill the area in between horizontal lines by drawing a rectangle and setting the axes ranges in a similar manner.

import numpy as np
import plotly.graph_objects as gox = np.arange(0, 4 * np.pi, 0.01)
y = np.sin(x)fig = go.Figure()
fig.add_trace(go.Scatter(x=x,y=y
))# hard-code the axes
fig.update_xaxes(range=[0, 4 * np.pi])
fig.update_yaxes(range=[-1.2, 1.2])# specify the corners of the rectangles
fig.update_layout(shapes=[dict(type="rect",xref="x",yref="y",x0="4",y0="-1.3",x1="5",y1="1.3",fillcolor="lightgray",opacity=0.4,line_width=0,layer="below"),dict(type="rect",xref="x",yref="y",x0="9",y0="-1.3",x1="10",y1="1.3",fillcolor="lightgray",opacity=0.4,line_width=0,layer="below"),]
)fig.show()

enter image description here

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

Related Q&A

Pythonic way to read file line by line?

Whats the Pythonic way to go about reading files line by line of the two methods below?with open(file, r) as f:for line in f:print lineorwith open(file, r) as f:for line in f.readlines():print lineOr …

Python Selenium clicking next button until the end

This is a follow up question from my first question, and I am trying to scrape a website and have Selenium click on next (until it cant be clicked) and collect the results as well.This is the html tag …

How can i detect one word with speech recognition in Python

I know how to detect speech with Python but this question is more specific: How can I make Python listening for only one word and then returns True if Python could recognize the word.I know, I could ju…

Finding matching and nonmatching items in lists

Im pretty new to Python and am getting a little confused as to what you can and cant do with lists. I have two lists that I want to compare and return matching and nonmatching elements in a binary form…

How to obtain better results using NLTK pos tag

I am just learning nltk using Python. I tried doing pos_tag on various sentences. But the results obtained are not accurate. How can I improvise the results ?broke = NN flimsy = NN crap = NNAlso I am …

Pandas apply on rolling with multi-column output

I am working on a code that would apply a rolling window to a function that would return multiple columns. Input: Pandas Series Expected output: 3-column DataFrame def fun1(series, ):# Some calculation…

Exceptions for the whole class

Im writing a program in Python, and nearly every method im my class is written like this: def someMethod(self):try:#...except someException:#in case of exception, do something here#e.g display a dialog…

Getting live output from asyncio subprocess

Im trying to use Python asyncio subprocesses to start an interactive SSH session and automatically input the password. The actual use case doesnt matter but it helps illustrate my problem. This is my c…

multi language support in python script

I have a large python (2.7) script that reads data from a database and generate pictures in pdf format. My pictures have strings for labels, etc... Now I want to add a multi language support for the sc…

Add date tickers to a matplotlib/python chart

I have a question that sounds simple but its driving me mad for some days. I have a historical time series closed in two lists: the first list is containing prices, lets say P = [1, 1.5, 1.3 ...] while…