1

I am trying to parse some dates from a CSV file, which are in "2014-07-01" format. Then I would like to put it on the x-axis of a plot

Below are my codes. Everything is fine as shown in the first image.

import csv
from matplotlib import pyplot as plt
from datetime import datetime

# Get high temperatures from file.
filename = 'sitka_weather_07-2014.csv'

with open(filename) as f:
    reader = csv.reader(f)

    highs = []
    dates = []
    for row in reader:
        high = int(row[1])
        highs.append(high)
        date = datetime.strptime(row[0], '%Y-%m-%d')
        dates.append(date)

#Plot data
fig = plt.figure(dpi=128, figsize = (10,6))
plt.plot(dates, highs, c='red')

#Format plot
plt.title("Daily high temperatures, July 2014", fontsize = 24)
plt.xlabel('', fontsize=16)

#draws the date labels diagonally to prevent them from overlapping
fig.autofmt_xdate()

plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)

plt.show()

But when I try to re-format the dates adding the strftime() method, the x-axis is messed up as shown in the second image. The only update I made is as below:

date = datetime.strptime(row[0], '%Y-%m-%d')


date = datetime.strptime(row[0], '%Y-%m-%d').strftime('%Y/%m/%d')

Anyone thoughts here on what went wrong? Any help is appreciated!

First image

Second image

Brian Hong
  • 21
  • 3

0 Answers0