0

I am trying to plot 1-minute data for a stock over the course of 5 days, when I try to plot I get straight lines between each day, how can I remove them? I have attached an image of the plot. Thanks so much in advance for the help. Here is my code:

import yfinance as yf 
import pandas as pd 
import matplotlib.pyplot as plt
%matplotlib inline


tickers = 'SPY'
data1 = yf.download(tickers, period="1wk", interval = '1m')
data = data1['Adj Close'].dropna()


data.plot()

actual plot

  • So either just plot the time part without the date, so that you get mutliple lines on the same scale, or you can look into making a Broken axis: https://matplotlib.org/stable/gallery/subplots_axes_and_figures/broken_axis.html – ALollz Jun 07 '21 at 20:51
  • Have you tried searching for other posts on this issue? Searching for "matplotlib line plot with breaks" brings up several hits, like [this](https://stackoverflow.com/questions/27266987/python-matplotlib-avoid-plotting-gaps) and [this](https://stackoverflow.com/questions/15652503/put-a-gap-break-in-a-line-plot). – AlexK Jun 07 '21 at 21:02
  • I tried numerous posts, however, none fixed my problem. I tried inputting NaN values for the last datapoint, and while it removes the long line, there is still a gap between each point. Thanks to all who have replied thus far. – Residualize Jun 07 '21 at 22:05
  • So you want there to be no space at all where there are currently those straight lines? Since your x-axis is a datetime axis, it does not remove sections of the plot where there are no data points. You can convert the data you use for the x-axis to string (if it is in the index of the dataframe, then with `data.index = data.index.astype('str')`). That will allow you to remove gaps. If this still does not help, please provide a sample of your dataframe and desired output. – AlexK Jun 07 '21 at 22:50
  • If your index contains datetime values (both date and time), you can apply a function to the index to convert it to string (`import datetime`, then `data.index = data.index.map(lambda x: datetime.datetime.strftime(x, format="%Y-%m-%d %H-%M-%S")`). – AlexK Jun 07 '21 at 22:59
  • [This](https://stackoverflow.com/questions/1273472/how-to-skip-empty-dates-weekends-in-a-financial-matplotlib-python-graph) post may help too. – AlexK Jun 07 '21 at 23:04
  • 1
    Alex both of these (especially the second one) work great for what I need. Thank you so much, I really appreciate you taking the time to help. Cheers! – Residualize Jun 07 '21 at 23:10

0 Answers0