Skip to content

Commit d8a80c6

Browse files
Doc: examples update
1 parent 7ff8a66 commit d8a80c6

File tree

5 files changed

+123
-76
lines changed

5 files changed

+123
-76
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: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""
2+
============================
3+
Grouped Barchart 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+
Credit: Josh Hemann
11+
"""
12+
13+
import numpy as np
14+
import matplotlib.pyplot as plt
15+
16+
17+
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
18+
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
19+
20+
ind = np.arange(len(men_means)) # the x locations for the groups
21+
width = 0.35 # the width of the bars
22+
23+
fig, ax = plt.subplots()
24+
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std,
25+
label='Men')
26+
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std,
27+
label='Women')
28+
29+
# Add some text for labels, title and custom x-axis tick labels, etc.
30+
ax.set_ylabel('Scores')
31+
ax.set_title('Scores by group and gender')
32+
ax.set_xticks(ind)
33+
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
34+
ax.legend()
35+
36+
37+
def autolabel(rects, xpos='center'):
38+
"""
39+
Attach a text label above each bar in *rects*, displaying its height.
40+
41+
*xpos* indicates which side to place the text w.r.t. the center of
42+
the bar. It can be one of the following {'center', 'right', 'left'}.
43+
"""
44+
45+
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
46+
offset = {'center': 0, 'right': 1, 'left': -1}
47+
48+
for rect in rects:
49+
height = rect.get_height()
50+
ax.annotate('{}'.format(height),
51+
xy=(rect.get_x() + rect.get_width() / 2, height),
52+
xytext=(offset[xpos]*3, 3), # use 3 points offset
53+
textcoords="offset points", # in both directions
54+
ha=ha[xpos], va='bottom')
55+
56+
57+
autolabel(rects1, "left")
58+
autolabel(rects2, "right")
59+
60+
fig.tight_layout()
61+
62+
plt.show()
63+
64+
65+
#############################################################################
66+
#
67+
# ------------
68+
#
69+
# References
70+
# """"""""""
71+
#
72+
# The use of the following functions, methods and classes is shown
73+
# in this example:
74+
75+
import matplotlib
76+
matplotlib.axes.Axes.bar
77+
matplotlib.pyplot.bar
78+
matplotlib.axes.Axes.annotate
79+
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: 38 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,14 @@
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.
1010
"""
1111

12-
###############################################################################
13-
# A bar plot with errorbars and height labels on individual bars.
14-
15-
# Credit: Josh Hemann
16-
17-
import numpy as np
18-
import matplotlib.pyplot as plt
19-
from matplotlib.ticker import MaxNLocator
20-
from collections import namedtuple
21-
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-
6512

6613
###############################################################################
6714
# This example comes from an application in which grade school gym
@@ -70,6 +17,13 @@ def autolabel(rects, xpos='center'):
7017
# children did. To extract the plotting code for demo purposes, we'll
7118
# just make up some data for little Johnny Doe...
7219

20+
import numpy as np
21+
import matplotlib.pyplot as plt
22+
from matplotlib.ticker import MaxNLocator
23+
from collections import namedtuple
24+
25+
np.random.seed(42)
26+
7327
Student = namedtuple('Student', ['name', 'grade', 'gender'])
7428
Score = namedtuple('Score', ['score', 'percentile'])
7529

@@ -178,24 +132,25 @@ def plot_student_results(student, scores, cohort_size):
178132

179133
rankStr = attach_ordinal(width)
180134
# The bars aren't wide enough to print the ranking inside
181-
if width < 5:
135+
if width < 40:
182136
# Shift the text to the right side of the right edge
183-
xloc = width + 1
137+
xloc = 5
184138
# Black against white background
185139
clr = 'black'
186140
align = 'left'
187141
else:
188142
# Shift the text to the left side of the right edge
189-
xloc = 0.98 * width
143+
xloc = -5
190144
# White on magenta
191145
clr = 'white'
192146
align = 'right'
193147

194148
# Center the text vertically in the bar
195149
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)
150+
label = ax1.annotate(rankStr, xy=(width, yloc), xytext=(xloc, 0),
151+
textcoords="offset points",
152+
ha=align, va='center',
153+
color=clr, weight='bold', clip_on=True)
199154
rect_labels.append(label)
200155

201156
# make the interactive mouse over give the bar title
@@ -219,3 +174,21 @@ def plot_student_results(student, scores, cohort_size):
219174

220175
arts = plot_student_results(student, scores, cohort_size)
221176
plt.show()
177+
178+
179+
#############################################################################
180+
#
181+
# ------------
182+
#
183+
# References
184+
# """"""""""
185+
#
186+
# The use of the following functions, methods and classes is shown
187+
# in this example:
188+
189+
import matplotlib
190+
matplotlib.axes.Axes.bar
191+
matplotlib.pyplot.bar
192+
matplotlib.axes.Axes.annotate
193+
matplotlib.pyplot.annotate
194+
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)