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

Skip to content

Commit 9f0afd2

Browse files
authored
Merge pull request #13399 from ImportanceOfBeingErnest/doc-examples-cleanup
Doc: examples update
2 parents 665cf51 + 64ac509 commit 9f0afd2

File tree

5 files changed

+127
-88
lines changed

5 files changed

+127
-88
lines changed

examples/images_contours_and_fields/interpolation_methods.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,9 @@
2828

2929
grid = np.random.rand(4, 4)
3030

31-
fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9.3, 6),
31+
fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6),
3232
subplot_kw={'xticks': [], 'yticks': []})
3333

34-
fig.subplots_adjust(left=0.03, right=0.97, hspace=0.3, wspace=0.05)
35-
3634
for ax, interp_method in zip(axs.flat, methods):
3735
ax.imshow(grid, interpolation=interp_method, cmap='viridis')
3836
ax.set_title(str(interp_method))
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""
2+
=============================
3+
Grouped bar chart with labels
4+
=============================
5+
6+
Bar charts are useful for visualizing counts, or summary statistics
7+
with error bars. This example shows a ways to create a grouped bar chart
8+
with Matplotlib and also how to annotate bars with labels.
9+
"""
10+
11+
import matplotlib
12+
import matplotlib.pyplot as plt
13+
import numpy as np
14+
15+
16+
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
17+
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
18+
19+
ind = np.arange(len(men_means)) # the x locations for the groups
20+
width = 0.35 # the width of the bars
21+
22+
fig, ax = plt.subplots()
23+
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std,
24+
label='Men')
25+
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std,
26+
label='Women')
27+
28+
# Add some text for labels, title and custom x-axis tick labels, etc.
29+
ax.set_ylabel('Scores')
30+
ax.set_title('Scores by group and gender')
31+
ax.set_xticks(ind)
32+
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
33+
ax.legend()
34+
35+
36+
def autolabel(rects, xpos='center'):
37+
"""
38+
Attach a text label above each bar in *rects*, displaying its height.
39+
40+
*xpos* indicates which side to place the text w.r.t. the center of
41+
the bar. It can be one of the following {'center', 'right', 'left'}.
42+
"""
43+
44+
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
45+
offset = {'center': 0, 'right': 1, 'left': -1}
46+
47+
for rect in rects:
48+
height = rect.get_height()
49+
ax.annotate('{}'.format(height),
50+
xy=(rect.get_x() + rect.get_width() / 2, height),
51+
xytext=(offset[xpos]*3, 3), # use 3 points offset
52+
textcoords="offset points", # in both directions
53+
ha=ha[xpos], va='bottom')
54+
55+
56+
autolabel(rects1, "left")
57+
autolabel(rects2, "right")
58+
59+
fig.tight_layout()
60+
61+
plt.show()
62+
63+
64+
#############################################################################
65+
#
66+
# ------------
67+
#
68+
# References
69+
# """"""""""
70+
#
71+
# The use of the following functions, methods and classes is shown
72+
# in this example:
73+
74+
matplotlib.axes.Axes.bar
75+
matplotlib.pyplot.bar
76+
matplotlib.axes.Axes.annotate
77+
matplotlib.pyplot.annotate

examples/pie_and_polar_charts/polar_bar.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""
22
=======================
3-
Pie chart on polar axis
3+
Bar chart on polar axis
44
=======================
55
66
Demo of bar plot on a polar axis.
@@ -17,14 +17,10 @@
1717
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
1818
radii = 10 * np.random.rand(N)
1919
width = np.pi / 4 * np.random.rand(N)
20+
colors = plt.cm.viridis(radii / 10.)
2021

2122
ax = plt.subplot(111, projection='polar')
22-
bars = ax.bar(theta, radii, width=width, bottom=0.0)
23-
24-
# Use custom colors and opacity
25-
for r, bar in zip(radii, bars):
26-
bar.set_facecolor(plt.cm.viridis(r / 10.))
27-
bar.set_alpha(0.5)
23+
ax.bar(theta, radii, width=width, bottom=0.0, color=colors, alpha=0.5)
2824

2925
plt.show()
3026

examples/statistics/barchart_demo.py

Lines changed: 44 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,27 @@
11
"""
2-
=============
3-
Barchart Demo
4-
=============
5-
6-
Bar charts of many shapes and sizes with Matplotlib.
2+
===================================
3+
Percentiles as horizontal bar chart
4+
===================================
75
86
Bar charts are useful for visualizing counts, or summary statistics
9-
with error bars. These examples show a few ways to do this with Matplotlib.
7+
with error bars. Also see the :doc:`/gallery/lines_bars_and_markers/barchart`
8+
or the :doc:`/gallery/lines_bars_and_markers/barh` example for simpler versions
9+
of those features.
10+
11+
This example comes from an application in which grade school gym
12+
teachers wanted to be able to show parents how their child did across
13+
a handful of fitness tests, and importantly, relative to how other
14+
children did. To extract the plotting code for demo purposes, we'll
15+
just make up some data for little Johnny Doe.
1016
"""
1117

12-
###############################################################################
13-
# A bar plot with errorbars and height labels on individual bars.
14-
15-
# Credit: Josh Hemann
16-
1718
import numpy as np
19+
import matplotlib
1820
import matplotlib.pyplot as plt
1921
from matplotlib.ticker import MaxNLocator
2022
from collections import namedtuple
2123

22-
23-
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
24-
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
25-
26-
ind = np.arange(len(men_means)) # the x locations for the groups
27-
width = 0.35 # the width of the bars
28-
29-
fig, ax = plt.subplots()
30-
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std,
31-
label='Men')
32-
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std,
33-
label='Women')
34-
35-
# Add some text for labels, title and custom x-axis tick labels, etc.
36-
ax.set_ylabel('Scores')
37-
ax.set_title('Scores by group and gender')
38-
ax.set_xticks(ind)
39-
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
40-
ax.legend()
41-
42-
43-
def autolabel(rects, xpos='center'):
44-
"""
45-
Attach a text label above each bar in *rects*, displaying its height.
46-
47-
*xpos* indicates which side to place the text w.r.t. the center of
48-
the bar. It can be one of the following {'center', 'right', 'left'}.
49-
"""
50-
51-
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
52-
offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} # x_txt = x + w*off
53-
54-
for rect in rects:
55-
height = rect.get_height()
56-
ax.text(rect.get_x() + rect.get_width() * offset[xpos], 1.01 * height,
57-
'{}'.format(height), ha=ha[xpos], va='bottom')
58-
59-
60-
autolabel(rects1, "left")
61-
autolabel(rects2, "right")
62-
63-
fig.tight_layout()
64-
65-
66-
###############################################################################
67-
# This example comes from an application in which grade school gym
68-
# teachers wanted to be able to show parents how their child did across
69-
# a handful of fitness tests, and importantly, relative to how other
70-
# children did. To extract the plotting code for demo purposes, we'll
71-
# just make up some data for little Johnny Doe...
24+
np.random.seed(42)
7225

7326
Student = namedtuple('Student', ['name', 'grade', 'gender'])
7427
Score = namedtuple('Score', ['score', 'percentile'])
@@ -142,10 +95,6 @@ def plot_student_results(student, scores, cohort_size):
14295

14396
# Plot a solid vertical gridline to highlight the median position
14497
ax1.axvline(50, color='grey', alpha=0.25)
145-
# set X-axis tick marks at the deciles
146-
cohort_label = ax1.text(.5, -.07, 'Cohort Size: {0}'.format(cohort_size),
147-
horizontalalignment='center', size='small',
148-
transform=ax1.transAxes)
14998

15099
# Set the right-hand Y-axis ticks and labels
151100
ax2 = ax1.twinx()
@@ -163,10 +112,11 @@ def plot_student_results(student, scores, cohort_size):
163112

164113
ax2.set_ylabel('Test Scores')
165114

166-
ax2.set_xlabel(('Percentile Ranking Across '
167-
'{grade} Grade {gender}s').format(
168-
grade=attach_ordinal(student.grade),
169-
gender=student.gender.title()))
115+
xlabel = ('Percentile Ranking Across {grade} Grade {gender}s\n'
116+
'Cohort Size: {cohort_size}')
117+
ax1.set_xlabel(xlabel.format(grade=attach_ordinal(student.grade),
118+
gender=student.gender.title(),
119+
cohort_size=cohort_size))
170120

171121
rect_labels = []
172122
# Lastly, write in the ranking inside each bar to aid in interpretation
@@ -178,24 +128,25 @@ def plot_student_results(student, scores, cohort_size):
178128

179129
rankStr = attach_ordinal(width)
180130
# The bars aren't wide enough to print the ranking inside
181-
if width < 5:
131+
if width < 40:
182132
# Shift the text to the right side of the right edge
183-
xloc = width + 1
133+
xloc = 5
184134
# Black against white background
185135
clr = 'black'
186136
align = 'left'
187137
else:
188138
# Shift the text to the left side of the right edge
189-
xloc = 0.98 * width
139+
xloc = -5
190140
# White on magenta
191141
clr = 'white'
192142
align = 'right'
193143

194144
# Center the text vertically in the bar
195145
yloc = rect.get_y() + rect.get_height() / 2
196-
label = ax1.text(xloc, yloc, rankStr, horizontalalignment=align,
197-
verticalalignment='center', color=clr, weight='bold',
198-
clip_on=True)
146+
label = ax1.annotate(rankStr, xy=(width, yloc), xytext=(xloc, 0),
147+
textcoords="offset points",
148+
ha=align, va='center',
149+
color=clr, weight='bold', clip_on=True)
199150
rect_labels.append(label)
200151

201152
# make the interactive mouse over give the bar title
@@ -205,8 +156,7 @@ def plot_student_results(student, scores, cohort_size):
205156
'ax': ax1,
206157
'ax_right': ax2,
207158
'bars': rects,
208-
'perc_labels': rect_labels,
209-
'cohort_label': cohort_label}
159+
'perc_labels': rect_labels}
210160

211161

212162
student = Student('Johnny Doe', 2, 'boy')
@@ -219,3 +169,20 @@ def plot_student_results(student, scores, cohort_size):
219169

220170
arts = plot_student_results(student, scores, cohort_size)
221171
plt.show()
172+
173+
174+
#############################################################################
175+
#
176+
# ------------
177+
#
178+
# References
179+
# """"""""""
180+
#
181+
# The use of the following functions, methods and classes is shown
182+
# in this example:
183+
184+
matplotlib.axes.Axes.bar
185+
matplotlib.pyplot.bar
186+
matplotlib.axes.Axes.annotate
187+
matplotlib.pyplot.annotate
188+
matplotlib.axes.Axes.twinx

examples/units/bar_unit_demo.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
Group barchart with units
44
=========================
55
6-
This is the same example as :doc:`/gallery/statistics/barchart_demo` in
6+
This is the same example as
7+
:doc:`the barchart</gallery/lines_bars_and_markers/barchart>` in
78
centimeters.
89
910
.. only:: builder_html

0 commit comments

Comments
 (0)