0

I've been attempting to plot data from a comma delimited csv file which contains a date and a float:

Date,Price (€)
01062017,20.90
02062017,30.90
03062017,40.90
04062017,60.90
05062017,50.90

I then attempt to plot this with the following code:

import matplotlib.pyplot as plt
import numpy as np
import datetime

dates,cost = np.loadtxt('price_check.csv',delimiter=',',skiprows=1,unpack=True)

xdates = [datetime.datetime.strptime(str(int(date)),'%d%m%Y') for date in dates]

fig = plt.figure()
ax = plt.subplot(111)
plt.plot(xdates, cost,'o-',label='Cost')
plt.legend(loc=4)
plt.ylabel('Price (Euro)')
plt.xlabel('date')
plt.gcf().autofmt_xdate()
plt.grid()
plt.savefig('sunglasses_cost.png')
plt.show()

However, when the data is plotted, it looks like the leading zero in in the date string is being dropped:

enter image description here

Is there an easy way for the full date to be used in the plot?

1
  • Why are you turning your date to integer before giving it to datetime.datetime.strptime()? That's what kills your leading zeros. Commented Jun 4, 2017 at 20:46

1 Answer 1

1

The problem are the dates, which are converted to integers and loose their leading zero. Then "01062017" becomes 1062017 and is then interpreted as (2017, 6, 10, 0, 0), so 2 digits as day, one digit month. For 5062017, because there is no 50th of june, it is interpreted differently and correctly as (2017, 6, 5, 0, 0).

The least invasive method to overcome this would be to format the string such that it always has 8 digist before datetime conversion:

xdates = [datetime.datetime.strptime('{:08}'.format(int(date)),'%d%m%Y') for date in dates]

This will then result in the correct plot. However, the xticklabels may show in an inconvenient way. This could be adjusted by choosing some locator and formatter

import matplotlib.dates as mdates
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))

enter code here

As a last comment: If you have the choice to select the format of your input file, it might be worth specifing it in a non-ambiguous way, e.g. 20170601.

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

Comments

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.