8000 Remove usage of numpy recarray · timhoffm/matplotlib@fc9b846 · GitHub
[go: up one dir, main page]

Skip to content

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit fc9b846

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

File tree

7 files changed

+33
-26
lines changed

7 files changed

+33
-26
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: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ 8000 -3,13 +3,15 @@
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`_ or `pandas.DataFrame`
7+
provide access to labelled data via string index access ``data[key]``.
8+
9+
For these data types, Matplotlib supports passing the whole datastructure via the
10+
``data`` keyword argument, and use the string names as plot function parameters, where
11+
you'd normally pass in your data.
12+
13+
.. _structured numpy array: https://numpy.org/doc/stable/user/basics.rec.html#structured-arrays
914
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.
1315
"""
1416

1517
import matplotlib.pyplot as plt

galleries/examples/ticks/centered_ticklabels.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@
2525
import matplotlib.ticker as ticker
2626

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

3131
fig, ax = plt.subplots()
32-
ax.plot(r.date, r.adj_close)
32+
ax.plot(r["date"], r["adj_close"])
3333

3434
ax.xaxis.set_major_locator(dates.MonthLocator())
3535
# 16 is a slight approximation since months differ in number of days.
@@ -45,5 +45,5 @@
4545
for label in ax.get_xticklabels(minor=True):
4646
label.set_horizontalalignment('center')
4747
imid = len(r) // 2
48-
ax.set_xlabel(str(r.date[imid].item().year))
48+
ax.set_xlabel(str(r["date"][imid].item().year))
4949
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: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,13 @@
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
129+
# Most methods will also parse a string-indexable object like a *dict*, a
130+
# `structured numpy array`_, or a `pandas.DataFrame`. Matplotlib allows you to
131131
# provide the ``data`` keyword argument and generate plots passing the
132132
# strings corresponding to the *x* and *y* variables.
133+
#
134+
# .. _structured numpy array: https://numpy.org/doc/stable/user/basics.rec.html#structured-arrays
135+
133136
np.random.seed(19680801) # seed the random number generator.
134137
data = {'a': np.arange(50),
135138
'c': np.random.randint(0, 50, 50),

0 commit comments

Comments
 (0)
0