Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ff3bd15

Browse files
authored
Merge pull request #15643 from anntzer/plot-datetimes
Fix examples claiming matplotlib can't plot np.datetime64.
2 parents c178929 + d45dc96 commit ff3bd15

4 files changed

Lines changed: 30 additions & 59 deletions

File tree

examples/recipes/common_date_problems.py

Lines changed: 16 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -24,23 +24,11 @@
2424
'2008-10-13', '2008-10-14'], dtype='datetime64[D]')
2525
2626
The dtype of the NumPy record array for the field ``date`` is ``datetime64[D]``
27-
which means it is a 64-bit `numpy.datetime64` in 'day' units. While this format
28-
is more portable, Matplotlib cannot plot this format natively yet. We can plot
29-
this data by changing the dates to `datetime.date` instances instead, which can
30-
be achieved by converting to an object array::
31-
32-
In [67]: r.date.astype('O')
33-
array([datetime.date(2004, 8, 19), datetime.date(2004, 8, 20),
34-
datetime.date(2004, 8, 23), ..., datetime.date(2008, 10, 10),
35-
datetime.date(2008, 10, 13), datetime.date(2008, 10, 14)],
36-
dtype=object)
37-
38-
The dtype of this converted array is now ``object`` and it is filled with
39-
datetime.date instances instead.
27+
which means it is a 64-bit `numpy.datetime64` in 'day' units.
4028
4129
If you plot the data, ::
4230
43-
In [67]: plot(r.date.astype('O'), r.close)
31+
In [67]: plot(r.date, r.close)
4432
Out[67]: [<matplotlib.lines.Line2D object at 0x92a6b6c>]
4533
4634
you will see that the x tick labels are all squashed together.
@@ -53,35 +41,28 @@
5341
with cbook.get_sample_data('goog.npz') as datafile:
5442
r = np.load(datafile)['price_data'].view(np.recarray)
5543

56-
# Matplotlib prefers datetime instead of np.datetime64.
57-
date = r.date.astype('O')
5844
fig, ax = plt.subplots()
59-
ax.plot(date, r.close)
45+
ax.plot(r.date, r.close)
6046
ax.set_title('Default date handling can cause overlapping labels')
6147

6248
###############################################################################
63-
# Another annoyance is that if you hover the mouse over the window and
64-
# look in the lower right corner of the matplotlib toolbar
65-
# (:ref:`navigation-toolbar`) at the x and y coordinates, you see that
66-
# the x locations are formatted the same way the tick labels are, e.g.,
67-
# "Dec 2004".
49+
# Another annoyance is that if you hover the mouse over the window and look in
50+
# the lower right corner of the Matplotlib toolbar (:ref:`navigation-toolbar`)
51+
# at the x and y coordinates, you see that the x locations are formatted the
52+
# same way the tick labels are, e.g., "Dec 2004".
6853
#
69-
# What we'd like is for the location in the toolbar to have
70-
# a higher degree of precision, e.g., giving us the exact date out mouse is
71-
# hovering over. To fix the first problem, we can use
72-
# :func:`matplotlib.figure.Figure.autofmt_xdate` and to fix the second
73-
# problem we can use the ``ax.fmt_xdata`` attribute which can be set to
74-
# any function that takes a scalar and returns a string. matplotlib has
75-
# a number of date formatters built in, so we'll use one of those.
54+
# What we'd like is for the location in the toolbar to have a higher degree of
55+
# precision, e.g., giving us the exact date out mouse is hovering over. To fix
56+
# the first problem, we can use `.Figure.autofmt_xdate` and to fix the second
57+
# problem we can use the ``ax.fmt_xdata`` attribute which can be set to any
58+
# function that takes a scalar and returns a string. Matplotlib has a number
59+
# of date formatters built in, so we'll use one of those.
7660

7761
fig, ax = plt.subplots()
78-
ax.plot(date, r.close)
79-
80-
# rotate and align the tick labels so they look better
62+
ax.plot(r.date, r.close)
63+
# Rotate and align the tick labels so they look better.
8164
fig.autofmt_xdate()
82-
83-
# use a more precise date string for the x axis locations in the
84-
# toolbar
65+
# Use a more precise date string for the x axis locations in the toolbar.
8566
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
8667
ax.set_title('fig.autofmt_xdate fixes the labels')
8768

examples/recipes/fill_between_alpha.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,14 @@
22
Fill Between and Alpha
33
======================
44
5-
The :meth:`~matplotlib.axes.Axes.fill_between` function generates a
6-
shaded region between a min and max boundary that is useful for
7-
illustrating ranges. It has a very handy ``where`` argument to
8-
combine filling with logical ranges, e.g., to just fill in a curve over
9-
some threshold value.
10-
11-
At its most basic level, ``fill_between`` can be use to enhance a
12-
graphs visual appearance. Let's compare two graphs of a financial
13-
times with a simple line plot on the left and a filled line on the
14-
right.
5+
The :meth:`~matplotlib.axes.Axes.fill_between` function generates a shaded
6+
region between a min and max boundary that is useful for illustrating ranges.
7+
It has a very handy ``where`` argument to combine filling with logical ranges,
8+
e.g., to just fill in a curve over some threshold value.
9+
10+
At its most basic level, ``fill_between`` can be use to enhance a graphs visual
11+
appearance. Let's compare two graphs of a financial times with a simple line
12+
plot on the left and a filled line on the right.
1513
"""
1614

1715
import matplotlib.pyplot as plt
@@ -21,15 +19,13 @@
2119
# load up some sample financial data
2220
with cbook.get_sample_data('goog.npz') as datafile:
2321
r = np.load(datafile)['price_data'].view(np.recarray)
24-
# Matplotlib prefers datetime instead of np.datetime64.
25-
date = r.date.astype('O')
2622
# create two subplots with the shared x and y axes
2723
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
2824

2925
pricemin = r.close.min()
3026

31-
ax1.plot(date, r.close, lw=2)
32-
ax2.fill_between(date, pricemin, r.close, facecolor='blue', alpha=0.5)
27+
ax1.plot(r.date, r.close, lw=2)
28+
ax2.fill_between(r.date, pricemin, r.close, facecolor='blue', alpha=0.5)
3329

3430
for ax in ax1, ax2:
3531
ax.grid(True)

examples/text_labels_and_annotations/date_index_formatter.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,10 @@
1818
with cbook.get_sample_data('goog.npz') as datafile:
1919
r = np.load(datafile)['price_data'].view(np.recarray)
2020
r = r[-30:] # get the last 30 days
21-
# Matplotlib works better with datetime.datetime than np.datetime64, but the
22-
# latter is more portable.
23-
date = r.date.astype('O')
2421

2522
# first we'll do it the default way, with gaps on weekends
2623
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4))
27-
ax1.plot(date, r.adj_close, 'o-')
24+
ax1.plot(r.date, r.adj_close, 'o-')
2825
ax1.set_title("Default")
2926
fig.autofmt_xdate()
3027

@@ -35,7 +32,7 @@
3532

3633
def format_date(x, pos=None):
3734
thisind = np.clip(int(x + 0.5), 0, N - 1)
38-
return date[thisind].strftime('%Y-%m-%d')
35+
return r.date[thisind].item().strftime('%Y-%m-%d')
3936

4037

4138
ax2.plot(ind, r.adj_close, 'o-')

examples/ticks_and_spines/centered_ticklabels.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,9 @@
2727
with cbook.get_sample_data('aapl.npz') as fh:
2828
r = np.load(fh)['price_data'].view(np.recarray)
2929
r = r[-250:] # get the last 250 days
30-
# Matplotlib works better with datetime.datetime than np.datetime64, but the
31-
# latter is more portable.
32-
date = r.date.astype('O')
3330

3431
fig, ax = plt.subplots()
35-
ax.plot(date, r.adj_close)
32+
ax.plot(r.date, r.adj_close)
3633

3734
ax.xaxis.set_major_locator(dates.MonthLocator())
3835
# 16 is a slight approximation since months differ in number of days.
@@ -47,5 +44,5 @@
4744
tick.label1.set_horizontalalignment('center')
4845

4946
imid = len(r) // 2
50-
ax.set_xlabel(str(date[imid].year))
47+
ax.set_xlabel(str(r.date[imid].item().year))
5148
plt.show()

0 commit comments

Comments
 (0)