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

Skip to content

Commit d4599b4

Browse files
committed
Remove usage of numpy recarray
Structured numpy arrays are more fundamental than recarrays and sufficient in all cases. Superseeds #26664.
1 parent 42336be commit d4599b4

File tree

7 files changed

+35
-29
lines changed

7 files changed

+35
-29
lines changed

galleries/examples/lines_bars_and_markers/fill_between_alpha.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,14 @@
1818
import matplotlib.cbook as cbook
1919

2020
# load up some sample financial data
21-
r = cbook.get_sample_data('goog.npz')['price_data'].view(np.recarray)
21+
r = cbook.get_sample_data('goog.npz')['price_data']
2222
# create two subplots with the shared x and y axes
2323
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
2424

25-
pricemin = r.close.min()
25+
pricemin = r["close"].min()
2626

27-
ax1.plot(r.date, r.close, lw=2)
28-
ax2.fill_between(r.date, pricemin, r.close, alpha=0.7)
27+
ax1.plot(r["date"], r["close"], lw=2)
28+
ax2.fill_between(r["date"], pricemin, r["close"], alpha=0.7)
2929

3030
for ax in ax1, ax2:
3131
ax.grid(True)

galleries/examples/lines_bars_and_markers/scatter_demo2.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@
1414
# low, close, volume, adj_close from the mpl-data/sample_data directory. The
1515
# record array stores the date as an np.datetime64 with a day unit ('D') in
1616
# the date column.
17-
price_data = cbook.get_sample_data('goog.npz')['price_data'].view(np.recarray)
17+
price_data = cbook.get_sample_data('goog.npz')['price_data']
1818
price_data = price_data[-250:] # get the most recent 250 trading days
1919

20-
delta1 = np.diff(price_data.adj_close) / price_data.adj_close[:-1]
20+
delta1 = np.diff(price_data["adj_close"]) / price_data["adj_close"][:-1]
2121

2222
# Marker size in units of points^2
23-
volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2
24-
close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2]
23+
volume = (15 * price_data["volume"][:-2] / price_data["volume"][0])**2
24+
close = 0.003 * price_data["close"][:-2] / 0.003 * price_data["open"][:-2]
2525

2626
fig, ax = plt.subplots()
2727
ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5)

galleries/examples/misc/keyword_plotting.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,14 @@
33
Plotting with keywords
44
======================
55
6-
There are some instances where you have data in a format that lets you
7-
access particular variables with strings: for example, with
8-
`numpy.recarray` or `pandas.DataFrame`.
6+
Some data structures, like dict, `structured numpy array
7+
<https://numpy.org/doc/stable/user/basics.rec.html#structured-arrays>`_
8+
or `pandas.DataFrame` provide access to labelled data via string index access
9+
``data[key]``.
910
10-
Matplotlib allows you to provide such an object with the ``data`` keyword
11-
argument. If provided, you may generate plots with the strings
12-
corresponding to these variables.
11+
For these data types, Matplotlib supports passing the whole datastructure via the
12+
``data`` keyword argument, and use the string names as plot function parameters, where
13+
you'd normally pass in your data.
1314
"""
1415

1516
import matplotlib.pyplot as plt

galleries/examples/ticks/centered_ticklabels.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,17 @@
1818
"""
1919

2020
import matplotlib.pyplot as plt
21-
import numpy as np
2221

2322
import matplotlib.cbook as cbook
2423
import matplotlib.dates as dates
2524
import matplotlib.ticker as ticker
2625

2726
# Load some financial data; Google's stock price
28-
r = cbook.get_sample_data('goog.npz')['price_data'].view(np.recarray)
27+
r = cbook.get_sample_data('goog.npz')['price_data']
2928
r = r[-250:] # get the last 250 days
3029

3130
fig, ax = plt.subplots()
32-
ax.plot(r.date, r.adj_close)
31+
ax.plot(r["date"], r["adj_close"])
3332

3433
ax.xaxis.set_major_locator(dates.MonthLocator())
3534
# 16 is a slight approximation since months differ in number of days.
@@ -45,5 +44,5 @@
4544
for label in ax.get_xticklabels(minor=True):
4645
label.set_horizontalalignment('center')
4746
imid = len(r) // 2
48-
ax.set_xlabel(str(r.date[imid].item().year))
47+
ax.set_xlabel(str(r["date"][imid].item().year))
4948
plt.show()

galleries/examples/ticks/date_index_formatter.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@
3232
fig.get_layout_engine().set(hspace=0.15)
3333

3434
# First we'll do it the default way, with gaps on weekends
35-
ax1.plot(r.date, r.adj_close, 'o-')
35+
ax1.plot(r["date"], r["adj_close"], 'o-')
3636

3737
# Highlight gaps in daily data
38-
gaps = np.flatnonzero(np.diff(r.date) > np.timedelta64(1, 'D'))
38+
gaps = np.flatnonzero(np.diff(r["date"]) > np.timedelta64(1, 'D'))
3939
for gap in r[['date', 'adj_close']][np.stack((gaps, gaps + 1)).T]:
4040
ax1.plot(gap.date, gap.adj_close, 'w--', lw=2)
4141
ax1.legend(handles=[ml.Line2D([], [], ls='--', label='Gaps in daily data')])
@@ -51,12 +51,12 @@
5151
def format_date(x, _):
5252
try:
5353
# convert datetime64 to datetime, and use datetime's strftime:
54-
return r.date[round(x)].item().strftime('%a')
54+
return r["date"][round(x)].item().strftime('%a')
5555
except IndexError:
5656
pass
5757

5858
# Create an index plot (x defaults to range(len(y)) if omitted)
59-
ax2.plot(r.adj_close, 'o-')
59+
ax2.plot(r["adj_close"], 'o-')
6060

6161
ax2.set_title("Plot y at Index Coordinates Using Custom Formatter")
6262
ax2.xaxis.set_major_formatter(format_date) # internally creates FuncFormatter
@@ -79,6 +79,6 @@ def __call__(self, x, pos=0):
7979
pass
8080

8181

82-
ax2.xaxis.set_major_formatter(MyFormatter(r.date, '%a'))
82+
ax2.xaxis.set_major_formatter(MyFormatter(r["date"], '%a'))
8383

8484
plt.show()

galleries/tutorials/pyplot.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,10 @@
106106
# =============================
107107
#
108108
# There are some instances where you have data in a format that lets you
109-
# access particular variables with strings. For example, with
110-
# `numpy.recarray` or `pandas.DataFrame`.
109+
# access particular variables with strings. For example, with `structured arrays`_
110+
# or `pandas.DataFrame`.
111+
#
112+
# .. _structured arrays: https://numpy.org/doc/stable/user/basics.rec.html#structured-arrays
111113
#
112114
# Matplotlib allows you to provide such an object with
113115
# the ``data`` keyword argument. If provided, then you may generate plots with

galleries/users_explain/quick_start.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,14 @@
126126
# b = np.matrix([[1, 2], [3, 4]])
127127
# b_asarray = np.asarray(b)
128128
#
129-
# Most methods will also parse an addressable object like a *dict*, a
130-
# `numpy.recarray`, or a `pandas.DataFrame`. Matplotlib allows you to
131-
# provide the ``data`` keyword argument and generate plots passing the
132-
# strings corresponding to the *x* and *y* variables.
129+
# Most methods will also parse a string-indexable object like a *dict*, a
130+
# `structured numpy array
131+
# <https://numpy.org/doc/stable/user/basics.rec.html#structured-arrays>`_, or a
132+
# `pandas.DataFrame`. Matplotlib allows you to provide the ``data`` keyword argument
133+
# and generate plots passing the strings corresponding to the *x* and *y* variables.
134+
#
135+
# .. _structured numpy array: https://numpy.org/doc/stable/user/basics.rec.html#structured-arrays
136+
133137
np.random.seed(19680801) # seed the random number generator.
134138
data = {'a': np.arange(50),
135139
'c': np.random.randint(0, 50, 50),

0 commit comments

Comments
 (0)