H a n d s o n, p r o j e c t b a s e d


Download 4.21 Mb.
Pdf ko'rish
bet271/344
Sana31.01.2024
Hajmi4.21 Mb.
#1818553
1   ...   267   268   269   270   271   272   273   274   ...   344
Bog'liq
Python Crash Course, 2nd Edition

Plotting Dates 
Now we can improve our temperature data plot by extracting dates for the 
daily highs and passing those highs and dates to 
plot()
, as shown here:
import csv
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/sitka_weather_07-2018_simple.csv'
sitka_highs.py


Downloading Data
339
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# Get dates and high temperatures from this file.
u
dates, highs = [], []
for row in reader:
v
current_date = datetime.strptime(row[2], '%Y-%m-%d')
high = int(row[5])
dates.append(current_date)
highs.append(high)
# Plot the high temperatures.
plt.style.use('seaborn')
fig, ax = plt.subplots()
w
ax.plot(dates, highs, c='red')
# Format plot.
plt.title("Daily high temperatures, July 2018", fontsize=24)
plt.xlabel('', fontsize=16)
x
fig.autofmt_xdate()
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.show()
We create two empty lists to store the dates and high temperatures from 
the file u. We then convert the data containing the date information (
row[2]

to a 
datetime
object v and append it to 
dates
. We pass the dates and the high 
temperature values to 
plot()
w. The call to 
fig.autofmt_xdate()
x draws the 
date labels diagonally to prevent them from overlapping. Fig ure 16-2 shows 
the improved graph.
Figure 16-2: The graph is more meaningful now that it has dates on the x-axis.


340
Chapter 16

Download 4.21 Mb.

Do'stlaringiz bilan baham:
1   ...   267   268   269   270   271   272   273   274   ...   344




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling