Skip to content

Commit 38c41ae

Browse files
authored
Merge pull request #17922 from timhoffm/doc-barcode
Rewrite the barcode example
2 parents 81a560c + 3e790dd commit 38c41ae

File tree

1 file changed

+30
-22
lines changed

1 file changed

+30
-22
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,40 @@
11
"""
2-
============
3-
Barcode Demo
4-
============
5-
6-
This demo shows how to produce a one-dimensional image, or "bar code".
2+
=======
3+
Barcode
4+
=======
5+
This demo shows how to produce a bar code.
6+
7+
The figure size is calculated so that the width in pixels is a multiple of the
8+
number of data points to prevent interpolation artifacts. Additionally, the
9+
``Axes`` is defined to span the whole figure and all ``Axis`` are turned off.
10+
11+
The data itself is rendered with `~.Axes.imshow` using
12+
13+
- ``code.reshape(1, -1)`` to turn the data into a 2D array with one row.
14+
- ``imshow(..., aspect='auto')`` to allow for non-square pixels.
15+
- ``imshow(..., interpolation='nearest')`` to prevent blurred edges. This
16+
should not happen anyway because we fine-tuned the figure width in pixels,
17+
but just to be safe.
718
"""
19+
820
import matplotlib.pyplot as plt
921
import numpy as np
1022

11-
# Fixing random state for reproducibility
12-
np.random.seed(19680801)
13-
14-
# the bar
15-
x = np.random.rand(500) > 0.7
16-
17-
barprops = dict(aspect='auto', cmap='binary', interpolation='nearest')
18-
19-
fig = plt.figure()
2023

21-
# a vertical barcode
22-
ax1 = fig.add_axes([0.1, 0.1, 0.1, 0.8])
23-
ax1.set_axis_off()
24-
ax1.imshow(x.reshape((-1, 1)), **barprops)
24+
code = np.array([
25+
1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1,
26+
0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0,
27+
1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1,
28+
1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1])
2529

26-
# a horizontal barcode
27-
ax2 = fig.add_axes([0.3, 0.4, 0.6, 0.2])
28-
ax2.set_axis_off()
29-
ax2.imshow(x.reshape((1, -1)), **barprops)
30+
pixel_per_bar = 4
31+
dpi = 100
3032

33+
fig = plt.figure(figsize=(len(code) * pixel_per_bar / dpi, 2), dpi=dpi)
34+
ax = fig.add_axes([0, 0, 1, 1]) # span the whole figure
35+
ax.set_axis_off()
36+
ax.imshow(code.reshape(1, -1), cmap='binary', aspect='auto',
37+
interpolation='nearest')
3138
plt.show()
3239

3340
#############################################################################
@@ -43,3 +50,4 @@
4350
import matplotlib
4451
matplotlib.axes.Axes.imshow
4552
matplotlib.pyplot.imshow
53+
matplotlib.figure.Figure.add_axes

0 commit comments

Comments
 (0)