0

I have 3 csv's with stock data, all from 2012-01-1 to 2017-01-01. I have used Pandas to make Dataframes out of them, and am instructed to turn them into this example plot: [Desired outcome][1]

My only issue is that Pandas isn't taking the 'Date' Series from my Dataframe to create the X axis of time like in the picture, instead I get an X axis of values 0-1400 [My failed plot][2] (I have 1258 dates, so it's getting the index of the date rather than the date itself).

This is my code for the plot right now:

ford['Open'].plot()
tesla['Open'].plot()
GM['Open'].plot(x=ford['Date'],figsize=(16,8),title='Open price',xlabel='Date')
plt.legend(['Ford','Tesla','GM'])

I have tried using the xticks argument and passing it tesla['Date'] (The name of the date series), but when I do I get this error:

ConversionError: Failed to convert value(s) to axis units: 0 2012-01-03 1 2012-01-04 2 2012-01-05 3 2012-01-06 4 2012-01-09 ...
1253 2016-12-23 1254 2016-12-27 1255 2016-12-28 1256 2016-12-29 1257 2016-12-30 Name: Date, Length: 1258, dtype: object

I couldn't find this particular issue on google and I've looked for an hour. I'm definitely missing something but I don't know what. Thanks for any help [1]: https://i.sstatic.net/bz8GU.png [2]: https://i.sstatic.net/lSihy.png

2 Answers 2

1

With pandas plots, you can create a graph by stacking each of them without specifying the x-axis. The data was obtained from Yahoo Finance in one-month units.

import matplotlib.pyplot as plt

fig = plt.figure()
ford['Open'].plot()
tesla['Open'].plot()
GM['Open'].plot(figsize=(16,8),title='Open price',xlabel='Date')
plt.legend(['Ford','Tesla','GM'])
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

This is the best answer for this particular problem (with pandas). See my answer below for more general pyplot labelling, especially if you want more control over your labels.
0

Select the index of the dates you want to display (say, one tick every 200 value), and use plt.xticks. Try this:

import numpy as np

ford['Open'].plot()
tesla['Open'].plot()
GM['Open'].plot()
plt.legend(['Ford','Tesla','GM'])
ticks = np.arange(0, len(ford['Date']), 200)
plt.xticks(ticks, ford['Date'][ticks])

3 Comments

Thank you so much, this worked! But I'm not sure why. What does the last [ticks] do to ford['Date']?
You're welcome. ford['Date'] is an array of all dates, and ticks contains the indexes of the dates you wish to keep for the plot labelling. So ford['Date'][ticks] returns an array with only the dates that will be displayed. Is that clearer?
Yes it is, thanks a lot I was really struggling with that one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.