|
1 | 1 | """
|
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 is calculated so that the width in pixel 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 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 save. |
7 | 18 | """
|
| 19 | + |
8 | 20 | importmatplotlib.pyplotasplt
|
9 | 21 | importnumpyasnp
|
10 | 22 |
|
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() |
20 | 23 |
|
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]) |
25 | 29 |
|
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 |
30 | 32 |
|
| 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') |
31 | 38 | plt.show()
|
32 | 39 |
|
33 | 40 | #############################################################################
|
|
43 | 50 | importmatplotlib
|
44 | 51 | matplotlib.axes.Axes.imshow
|
45 | 52 | matplotlib.pyplot.imshow
|
| 53 | +matplotlib.figure.Figure.add_axes |