'Problems using Rangebreaks plotly
I was making a time series graph using Plotly however the x-axis has too many labels. I did some research and I think that I could use Rangebreaks to help fix this issue but I'm not sure. I would ideally like there to be fewer x-axis labels. I'll disclose my code below.
import pandas as pd
import yfinance as yf
import datetime as dt
import plotly.graph_objects as go
#Initial data & get dataframe
start = dt.date(2022,3,1)
end = dt.date(2022,3,7)
ticker = 'SPY'
df = yf.download(ticker,start,end,progress=False,interval='1m')
#Make Graph
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df.index,
y=df['Adj Close'],
mode='lines'))
fig.update_layout(xaxis={'type':'category'})
fig.show()
Here is what the graph looks like:

I did actually change the x-axis type on my code but this was done for a reason, to prevent my graph from having large gaps in it like so:

Solution 1:[1]
- looking at data, trading is closed from 4pm to 9:30am
- this can be simply excluded:
fig.update_xaxes(
rangebreaks=[
dict(bounds=[16, 9.5], pattern="hour"), # hide hours from 4pm to 9:30am
]
)
full code
import pandas as pd
import yfinance as yf
import datetime as dt
import plotly.graph_objects as go
# Initial data & get dataframe
start = dt.date(2022, 3, 1)
end = dt.date(2022, 3, 7)
ticker = "SPY"
df = yf.download(ticker, start, end, progress=False, interval="1m")
# Make Graph
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.index, y=df["Adj Close"], mode="lines"))
# fig.update_layout(xaxis={'type':'category'})
fig.update_xaxes(
rangebreaks=[
dict(bounds=[16, 9.5], pattern="hour"), # hide hours from 4pm to 9:30am
]
)
output
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rob Raymond |

