8000 Add test for added parameters · matplotlib/matplotlib@34df06a · GitHub
[go: up one dir, main page]

Skip to content

Commit 34df06a

Browse files
committed
Add test for added parameters
Specify extensions for test Added modified baseline images Modified test for histogram with single parameters Fixed test Add modified baseline images Made changes concise according to suggestion Made a more detailed gallery example Fix Docs Added whats new note, documentation for vectorization, doc fix Added new test, and reverted changes in old test Added baseline images Modified test to pass codecov, added plot in whats new entry Fix test Added baseline images Altered whats new entry, docs and gallery example Resolved edgecolor and facecolor setting Minor fix Fix docs Modified files to include facecolor and added test Removed figsize from test Add multiple baseline image names Fixed test? Fixed test? Removed parametrize usage Add baseline images Add baseline image Fix docs Fix docs Deleted baseline images, changed test Fix test Fix test Handled None array passing to color Handled passing None list Modified nested patch condition Minor Fix Grammar nits Modified test, edited None handling in sequence so that it errors out
1 parent 0e52daa commit 34df06a

File tree

4 files changed

+197
-40
lines changed

4 files changed

+197
-40
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
Vectorize ``hatch``, ``edgecolor``, ``facecolor``, ``linewidth`` and ``linestyle`` in *hist* methods
2+
----------------------------------------------------------------------------------------------------
3+
4+
The parameters ``hatch``, ``edgecolor``, ``facecolor``, ``linewidth`` and ``linestyle``
5+
of the `~matplotlib.axes.Axes.hist` method are now vectorized.
6+
This means that you can pass in unique parameters for each histogram that is generated
7+
when the input *x* has multiple datasets.
8+
9+
10+
.. plot::
11+
:include-source: true
12+
:alt: Four charts, each displaying stacked histograms of three Poisson distributions. Each chart differentiates the histograms using various parameters: ax1 uses different linewidths, ax2 uses different hatches, ax3 uses different edgecolors, and ax4 uses different facecolors. Each histogram in ax1 and ax3 also has a different edgecolor.
13+
14+
import matplotlib.pyplot as plt
15+
import numpy as np
16+
np.random.seed(19680801)
17+
18+
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(9, 9))
19+
20+
data1 = np.random.poisson(5, 1000)
21+
data2 = np.random.poisson(7, 1000)
22+
data3 = np.random.poisson(10, 1000)
23+
24+
labels = ["Data 1", "Data 2", "Data 3"]
25+
26+
ax1.hist([data1, data2, data3], bins=range(17), histtype="step", stacked=True,
27+
edgecolor=["red", "green", "blue"], linewidth=[1, 2, 3])
28+
ax1.set_title("Different linewidths")
29+
ax1.legend(labels)
30+
31+
ax2.hist([data1, data2, data3], bins=range(17), histtype="barstacked",
32+
hatch=["/", ".", "*"])
33+
ax2.set_title("Different hatch patterns")
34+
ax2.legend(labels)
35+
36+
ax3.hist([data1, data2, data3], bins=range(17), histtype="bar", fill=False,
37+
edgecolor=["red", "green", "blue"], linestyle=["--", "-.", ":"])
38+
ax3.set_title("Different linestyles")
39+
ax3.legend(labels)
40+
41+
ax4.hist([data1, data2, data3], bins=range(17), histtype="barstacked",
42+
facecolor=["red", "green", "blue"])
43+
ax4.set_title("Different facecolors")
44+
ax4.legend(labels)
45+
46+
plt.show()

galleries/examples/statistics/histogram_multihist.py

Lines changed: 92 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
select these parameters:
1616
http://docs.astropy.org/en/stable/visualization/histogram.html
1717
"""
18-
18+
# %%
1919
import matplotlib.pyplot as plt
2020
import numpy as np
2121

@@ -27,29 +27,111 @@
2727
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(nrows=2, ncols=2)
2828

2929
colors = ['red', 'tan', 'lime']
30-
ax0.hist(x, n_bins, density=True, histtype='bar', color=colors,
31-
label=colors, hatch=['o', '*', '.'],
32-
edgecolor=['black', 'red', 'blue'], linewidth=[1, 2, 3])
30+
ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
3331
ax0.legend(prop={'size': 10})
3432
ax0.set_title('bars with legend')
3533

36-
ax1.hist(
37-
x, n_bins, density=True, histtype="bar", stacked=True,
38-
edgecolor=["black", "yellow", "blue"])
34+
ax1.hist(x, n_bins, density=True, histtype='bar', stacked=True)
3935
ax1.set_title('stacked bar')
4036

41-
ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False,
42-
linewidth=[1, 2, 3])
37+
ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)
4338
ax2.set_title('stack step (unfilled)')
4439

4540
# Make a multiple-histogram of data-sets with different length.
4641
x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
47-
ax3.hist(x_multi, n_bins, histtype='bar', hatch=['\\', '/', '-'])
42+
ax3.hist(x_multi, n_bins, histtype='bar')
4843
ax3.set_title('different sample sizes')
4944

5045
fig.tight_layout()
5146
plt.show()
5247

48+
# %%
49+
# -----------------------------------
50+
# Setting properties for each dataset
51+
# -----------------------------------
52+
#
53+
# Plotting bar charts with datasets differentiated using:
54+
#
55+
# * edgecolors
56+
# * facecolors
57+
# * hatches
58+
# * linewidths
59+
# * linestyles
60+
#
61+
#
62+
# Histograms with Edge-Colors
63+
# ...........................
64+
65+
fig, ax = plt.subplots()
66+
67+
edgecolors = ['green', 'red', 'blue']
68+
69+
ax.hist(x, n_bins, fill=False, histtype="step", stacked=True,
70+
edgecolor=edgecolors, label=edgecolors)
71+
ax.legend()
72+
ax.set_title('Stacked Steps with Edgecolors')
73+
74+
plt.show()
75+
76+
# %%
77+
# Face colors
78+
# ...........................
79+
80+
fig, ax = plt.subplots()
81+
82+
facecolors = ['green', 'red', 'blue']
83+
84+
ax.hist(x, n_bins, histtype="barstacked", facecolor=facecolors, label=facecolors)
85+
ax.legend()
86+
ax.set_title("Bars with different Facecolors")
87+
88+
plt.show()
89+
90+
# %%
91+
# Hatches
92+
# .......................
93+
94+
fig, ax = plt.subplots()
95+
96+
hatches = [".", "o", "x"]
97+
98+
ax.hist(x, n_bins, histtype="barstacked", hatch=hatches, label=hatches)
99+
ax.legend()
100+
ax.set_title("Hatches on Stacked Bars")
101+
102+
plt.show()
103+
104+
# %%
105+
# Linewidths
106+
# ..........................
107+
108+
fig, ax = plt.subplots()
109+
110+
linewidths = [1, 2, 3]
111+
edgecolors = ["green", "red", "blue"]
112+
113+
ax.hist(x, n_bins, fill=False, histtype="bar", linewidth=linewidths,
114+
edgecolor=edgecolors, label=linewidths)
115+
ax.legend()
116+
ax.set_title("Bars with Linewidths")
117+
118+
plt.show()
119+
120+
# %%
121+
# LineStyles
122+
# ..........................
123+
124+
fig, ax = plt.subplots()
125+
126+
linestyles = ['-', ':', '--']
127+
128+
ax.hist(x, n_bins, fill=False, histtype='bar', linestyle=linestyles,
129+
edgecolor=edgecolors, label=linestyles)
130+
ax.legend()
131+
ax.set_title('Bars with Linestyles')
132+
133+
plt.show()
134+
53135
# %%
54136
#
55137
# .. admonition:: References

lib/matplotlib/axes/_axes.py

Lines changed: 26 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -6937,7 +6937,10 @@ def hist(self, x, bins=None, range=None, density=False, weights=None,
69376937
DATA_PARAMETER_PLACEHOLDER
69386938
69396939
**kwargs
6940-
`~matplotlib.patches.Patch` properties
6940+
`~matplotlib.patches.Patch` properties. The following properties
6941+
additionally accept a sequence of values corresponding to the
6942+
datasets in *x*:
6943+
*edgecolors*, *facecolors*, *linewidths*, *linestyles*, *hatches*.
69416944
69426945
See Also
69436946
--------
@@ -7211,39 +7214,32 @@ def hist(self, x, bins=None, range=None, density=False, weights=None,
72117214
# cast each element to str, but keep a single str as it.
72127215
labels = [] if label is None else np.atleast_1d(np.asarray(label, str))
72137216

7214-
if 'hatch' in kwargs:
7215-
if not isinstance(kwargs['hatch'], str):
7216-
hatches = itertools.cycle(kwargs['hatch'])
7217-
else:
7218-
hatches = itertools.cycle([kwargs['hatch']])
7219-
7220-
if 'edgecolor' in kwargs:
7221-
if not isinstance(kwargs['edgecolor'], str):
7222-
edgecolors = itertools.cycle(kwargs['edgecolor'])
7223-
else:
7224-
edgecolors = itertools.cycle([kwargs['edgecolor']])
7217+
if histtype == "step":
7218+
edgecolors = itertools.cycle(np.atleast_1d(kwargs.get('edgecolor',
7219+
colors)))
7220+
else:
7221+
edgecolors = itertools.cycle(np.atleast_1d(kwargs.get("edgecolor", None)))
72257222

7226-
if 'linewidth' in kwargs:
7227-
if isinstance(kwargs['linewidth'], list or tuple):
7228-
linewidths = itertools.cycle(kwargs['linewidth'])
7229-
else:
7230-
linewidths = itertools.cycle([kwargs['linewidth']])
7223+
facecolors = itertools.cycle(np.atleast_1d(kwargs.get('facecolor', colors)))
7224+
hatches = itertools.cycle(np.atleast_1d(kwargs.get('hatch', None)))
7225+
linewidths = itertools.cycle(np.atleast_1d(kwargs.get('linewidth', None)))
7226+
linestyles = itertools.cycle(np.atleast_1d(kwargs.get('linestyle', None)))
72317227

72327228
for patch, lbl in itertools.zip_longest(patches, labels):
7233-
if patch:
7234-
p = patch[0]
7235-
if 'hatch' in kwargs:
7236-
kwargs['hatch'] = next(hatches)
7237-
if 'edgecolor' in kwargs:
7238-
kwargs['edgecolor'] = next(edgecolors)
7239-
if 'linewidth' in kwargs:
7240-
kwargs['linewidth'] = next(linewidths)
7229+
p = patch[0]
7230+
kwargs.update({
7231+
'hatch': next(hatches),
7232+
'linewidth': next(linewidths),
7233+
'linestyle': next(linestyles),
7234+
'edgecolor': next(edgecolors),
7235+
'facecolor': next(facecolors),
7236+
})
7237+
p._internal_update(kwargs)
7238+
if lbl is not None:
7239+
p.set_label(lbl)
7240+
for p in patch[1:]:
72417241
p._internal_update(kwargs)
7242-
if lbl is not None:
7243-
p.set_label(lbl)
7244-
for p in patch[1:]:
7245-
p._internal_update(kwargs)
7246-
p.set_label('_nolegend_')
7242+
p.set_label('_nolegend_')
72477243

72487244
if nx == 1:
72497245
return tops[0], bins, patches[0]

lib/matplotlib/tests/test_axes.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4603,6 +4603,39 @@ def test_hist_stacked_bar():
46034603
ax.legend(loc='upper right', bbox_to_anchor=(1.0, 1.0), ncols=1)
46044604

46054605

4606+
@pytest.mark.parametrize("histtype", ["step", "stepfilled"])
4607+
@pytest.mark.parametrize("color", [["blue", "green", "brown"], None])
4608+
@pytest.mark.parametrize("edgecolor", [["red", "black", "blue"], [None]*3])
4609+
@pytest.mark.parametrize("facecolor", [["blue", "green", "brown"], [None]*3])
4610+
@check_figures_equal(extensions=["png"])
4611+
def test_hist_vectorized_params(fig_test, fig_ref, histtype, color, edgecolor,
4612+
facecolor):
4613+
np.random.seed(19680801)
4614+
x = [np.random.randn(n) for n in [2000, 5000, 10000]]
4615+
linewidth = [1, 1.5, 2]
4616+
hatch = ["/", "\\", "."]
4617+
linestyle = ["-", "--", ":"]
4618+
4619+
facecolor = facecolor if facecolor[0] is not None else color
4620+
if histtype == "step":
4621+
edgecolor = edgecolor if edgecolor[0] is not None else color
4622+
4623+
_, bins, _ = fig_test.subplots().hist(x, bins=10, histtype=histtype, color=color,
4624+
edgecolor=edgecolor, facecolor=facecolor,
4625+
linewidth=linewidth, hatch=hatch,
4626+
linestyle=linestyle)
4627+
ref_ax = fig_ref.subplots()
4628+
color = [None]*3 if color is None else color
4629+
edgecolor = [None]*3 if edgecolor is None else edgecolor
4630+
facecolor = [None]*3 if facecolor is None else facecolor
4631+
4632+
for i in range(2, -1, -1):
4633+
ref_ax.hist(x[i], bins=bins, histtype=histtype, color=color[i],
4634+
edgecolor=edgecolor[i], facecolor=facecolor[i],
4635+
linewidth=linewidth[i], hatch=hatch[i],
4636+
linestyle=linestyle[i])
4637+
4638+
46064639
def test_hist_barstacked_bottom_unchanged():
46074640
b = np.array([10, 20])
46084641
plt.hist([[0, 1], [0, 1]], 2, histtype="barstacked", bottom=b)

0 commit comments

Comments
 (0)
0