From 64ac509a6cec89592c6140eebcd9058cb87044f0 Mon Sep 17 00:00:00 2001 From: ImportanceOfBeingErnest Date: Sun, 10 Feb 2019 18:09:29 +0100 Subject: [PATCH] Doc: examples update --- .../interpolation_methods.py | 4 +- examples/lines_bars_and_markers/barchart.py | 77 +++++++++++ examples/pie_and_polar_charts/polar_bar.py | 10 +- examples/statistics/barchart_demo.py | 121 +++++++----------- examples/units/bar_unit_demo.py | 3 +- 5 files changed, 127 insertions(+), 88 deletions(-) create mode 100644 examples/lines_bars_and_markers/barchart.py diff --git a/examples/images_contours_and_fields/interpolation_methods.py b/examples/images_contours_and_fields/interpolation_methods.py index 08efa9f5d5df..f21866ecd375 100644 --- a/examples/images_contours_and_fields/interpolation_methods.py +++ b/examples/images_contours_and_fields/interpolation_methods.py @@ -28,11 +28,9 @@ grid = np.random.rand(4, 4) -fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9.3, 6), +fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6), subplot_kw={'xticks': [], 'yticks': []}) -fig.subplots_adjust(left=0.03, right=0.97, hspace=0.3, wspace=0.05) - for ax, interp_method in zip(axs.flat, methods): ax.imshow(grid, interpolation=interp_method, cmap='viridis') ax.set_title(str(interp_method)) diff --git a/examples/lines_bars_and_markers/barchart.py b/examples/lines_bars_and_markers/barchart.py new file mode 100644 index 000000000000..4fd2f79299a9 --- /dev/null +++ b/examples/lines_bars_and_markers/barchart.py @@ -0,0 +1,77 @@ +""" +============================= +Grouped bar chart with labels +============================= + +Bar charts are useful for visualizing counts, or summary statistics +with error bars. This example shows a ways to create a grouped bar chart +with Matplotlib and also how to annotate bars with labels. +""" + +import matplotlib +import matplotlib.pyplot as plt +import numpy as np + + +men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2) +women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3) + +ind = np.arange(len(men_means)) # the x locations for the groups +width = 0.35 # the width of the bars + +fig, ax = plt.subplots() +rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, + label='Men') +rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, + label='Women') + +# Add some text for labels, title and custom x-axis tick labels, etc. +ax.set_ylabel('Scores') +ax.set_title('Scores by group and gender') +ax.set_xticks(ind) +ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) +ax.legend() + + +def autolabel(rects, xpos='center'): + """ + Attach a text label above each bar in *rects*, displaying its height. + + *xpos* indicates which side to place the text w.r.t. the center of + the bar. It can be one of the following {'center', 'right', 'left'}. + """ + + ha = {'center': 'center', 'right': 'left', 'left': 'right'} + offset = {'center': 0, 'right': 1, 'left': -1} + + for rect in rects: + height = rect.get_height() + ax.annotate('{}'.format(height), + xy=(rect.get_x() + rect.get_width() / 2, height), + xytext=(offset[xpos]*3, 3), # use 3 points offset + textcoords="offset points", # in both directions + ha=ha[xpos], va='bottom') + + +autolabel(rects1, "left") +autolabel(rects2, "right") + +fig.tight_layout() + +plt.show() + + +############################################################################# +# +# ------------ +# +# References +# """""""""" +# +# The use of the following functions, methods and classes is shown +# in this example: + +matplotlib.axes.Axes.bar +matplotlib.pyplot.bar +matplotlib.axes.Axes.annotate +matplotlib.pyplot.annotate diff --git a/examples/pie_and_polar_charts/polar_bar.py b/examples/pie_and_polar_charts/polar_bar.py index 58fd07fad682..2d9a8dee3252 100644 --- a/examples/pie_and_polar_charts/polar_bar.py +++ b/examples/pie_and_polar_charts/polar_bar.py @@ -1,6 +1,6 @@ """ ======================= -Pie chart on polar axis +Bar chart on polar axis ======================= Demo of bar plot on a polar axis. @@ -17,14 +17,10 @@ theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False) radii = 10 * np.random.rand(N) width = np.pi / 4 * np.random.rand(N) +colors = plt.cm.viridis(radii / 10.) ax = plt.subplot(111, projection='polar') -bars = ax.bar(theta, radii, width=width, bottom=0.0) - -# Use custom colors and opacity -for r, bar in zip(radii, bars): - bar.set_facecolor(plt.cm.viridis(r / 10.)) - bar.set_alpha(0.5) +ax.bar(theta, radii, width=width, bottom=0.0, color=colors, alpha=0.5) plt.show() diff --git a/examples/statistics/barchart_demo.py b/examples/statistics/barchart_demo.py index 56643f3aec39..4e66855bc56e 100644 --- a/examples/statistics/barchart_demo.py +++ b/examples/statistics/barchart_demo.py @@ -1,74 +1,27 @@ """ -============= -Barchart Demo -============= - -Bar charts of many shapes and sizes with Matplotlib. +=================================== +Percentiles as horizontal bar chart +=================================== Bar charts are useful for visualizing counts, or summary statistics -with error bars. These examples show a few ways to do this with Matplotlib. +with error bars. Also see the :doc:`/gallery/lines_bars_and_markers/barchart` +or the :doc:`/gallery/lines_bars_and_markers/barh` example for simpler versions +of those features. + +This example comes from an application in which grade school gym +teachers wanted to be able to show parents how their child did across +a handful of fitness tests, and importantly, relative to how other +children did. To extract the plotting code for demo purposes, we'll +just make up some data for little Johnny Doe. """ -############################################################################### -# A bar plot with errorbars and height labels on individual bars. - -# Credit: Josh Hemann - import numpy as np +import matplotlib import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from collections import namedtuple - -men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2) -women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3) - -ind = np.arange(len(men_means)) # the x locations for the groups -width = 0.35 # the width of the bars - -fig, ax = plt.subplots() -rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, - label='Men') -rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, - label='Women') - -# Add some text for labels, title and custom x-axis tick labels, etc. -ax.set_ylabel('Scores') -ax.set_title('Scores by group and gender') -ax.set_xticks(ind) -ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) -ax.legend() - - -def autolabel(rects, xpos='center'): - """ - Attach a text label above each bar in *rects*, displaying its height. - - *xpos* indicates which side to place the text w.r.t. the center of - the bar. It can be one of the following {'center', 'right', 'left'}. - """ - - ha = {'center': 'center', 'right': 'left', 'left': 'right'} - offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} # x_txt = x + w*off - - for rect in rects: - height = rect.get_height() - ax.text(rect.get_x() + rect.get_width() * offset[xpos], 1.01 * height, - '{}'.format(height), ha=ha[xpos], va='bottom') - - -autolabel(rects1, "left") -autolabel(rects2, "right") - -fig.tight_layout() - - -############################################################################### -# This example comes from an application in which grade school gym -# teachers wanted to be able to show parents how their child did across -# a handful of fitness tests, and importantly, relative to how other -# children did. To extract the plotting code for demo purposes, we'll -# just make up some data for little Johnny Doe... +np.random.seed(42) Student = namedtuple('Student', ['name', 'grade', 'gender']) Score = namedtuple('Score', ['score', 'percentile']) @@ -142,10 +95,6 @@ def plot_student_results(student, scores, cohort_size): # Plot a solid vertical gridline to highlight the median position ax1.axvline(50, color='grey', alpha=0.25) - # set X-axis tick marks at the deciles - cohort_label = ax1.text(.5, -.07, 'Cohort Size: {0}'.format(cohort_size), - horizontalalignment='center', size='small', - transform=ax1.transAxes) # Set the right-hand Y-axis ticks and labels ax2 = ax1.twinx() @@ -163,10 +112,11 @@ def plot_student_results(student, scores, cohort_size): ax2.set_ylabel('Test Scores') - ax2.set_xlabel(('Percentile Ranking Across ' - '{grade} Grade {gender}s').format( - grade=attach_ordinal(student.grade), - gender=student.gender.title())) + xlabel = ('Percentile Ranking Across {grade} Grade {gender}s\n' + 'Cohort Size: {cohort_size}') + ax1.set_xlabel(xlabel.format(grade=attach_ordinal(student.grade), + gender=student.gender.title(), + cohort_size=cohort_size)) rect_labels = [] # Lastly, write in the ranking inside each bar to aid in interpretation @@ -178,24 +128,25 @@ def plot_student_results(student, scores, cohort_size): rankStr = attach_ordinal(width) # The bars aren't wide enough to print the ranking inside - if width < 5: + if width < 40: # Shift the text to the right side of the right edge - xloc = width + 1 + xloc = 5 # Black against white background clr = 'black' align = 'left' else: # Shift the text to the left side of the right edge - xloc = 0.98 * width + xloc = -5 # White on magenta clr = 'white' align = 'right' # Center the text vertically in the bar yloc = rect.get_y() + rect.get_height() / 2 - label = ax1.text(xloc, yloc, rankStr, horizontalalignment=align, - verticalalignment='center', color=clr, weight='bold', - clip_on=True) + label = ax1.annotate(rankStr, xy=(width, yloc), xytext=(xloc, 0), + textcoords="offset points", + ha=align, va='center', + color=clr, weight='bold', clip_on=True) rect_labels.append(label) # make the interactive mouse over give the bar title @@ -205,8 +156,7 @@ def plot_student_results(student, scores, cohort_size): 'ax': ax1, 'ax_right': ax2, 'bars': rects, - 'perc_labels': rect_labels, - 'cohort_label': cohort_label} + 'perc_labels': rect_labels} student = Student('Johnny Doe', 2, 'boy') @@ -219,3 +169,20 @@ def plot_student_results(student, scores, cohort_size): arts = plot_student_results(student, scores, cohort_size) plt.show() + + +############################################################################# +# +# ------------ +# +# References +# """""""""" +# +# The use of the following functions, methods and classes is shown +# in this example: + +matplotlib.axes.Axes.bar +matplotlib.pyplot.bar +matplotlib.axes.Axes.annotate +matplotlib.pyplot.annotate +matplotlib.axes.Axes.twinx diff --git a/examples/units/bar_unit_demo.py b/examples/units/bar_unit_demo.py index 228fded53620..e6a6a7687a61 100644 --- a/examples/units/bar_unit_demo.py +++ b/examples/units/bar_unit_demo.py @@ -3,7 +3,8 @@ Group barchart with units ========================= -This is the same example as :doc:`/gallery/statistics/barchart_demo` in +This is the same example as +:doc:`the barchart` in centimeters. .. only:: builder_html