diff --git a/.flake8 b/.flake8 index 44ab9b8701f8..da79a558d075 100644 --- a/.flake8 +++ b/.flake8 @@ -170,7 +170,7 @@ per-file-ignores = examples/lines_bars_and_markers/joinstyle.py: E402 examples/lines_bars_and_markers/scatter_piecharts.py: E402 examples/lines_bars_and_markers/span_regions.py: E402 - examples/misc/agg_oo_sgskip.py: E402 + examples/misc/agg_buffer.py: E402 examples/misc/anchored_artists.py: E501 examples/misc/contour_manual.py: E501 examples/misc/font_indexing.py: E501 @@ -263,6 +263,7 @@ per-file-ignores = examples/text_labels_and_annotations/tex_demo.py: E402 examples/text_labels_and_annotations/watermark_text.py: E402 examples/ticks_and_spines/auto_ticks.py: E501 + examples/user_interfaces/canvasagg.py: E402 examples/user_interfaces/embedding_in_gtk3_panzoom_sgskip.py: E402 examples/user_interfaces/embedding_in_gtk3_sgskip.py: E402 examples/user_interfaces/embedding_in_qt_sgskip.py: E402 diff --git a/doc/faq/howto_faq.rst b/doc/faq/howto_faq.rst index 12633e8b2d91..dd48905e27f8 100644 --- a/doc/faq/howto_faq.rst +++ b/doc/faq/howto_faq.rst @@ -662,7 +662,7 @@ For more on configuring your backend, see Alternatively, you can avoid pylab/pyplot altogether, which will give you a little more control, by calling the API directly as shown in -:doc:`/gallery/misc/agg_oo_sgskip`. +:doc:`/gallery/user_interfaces/canvasagg`. You can either generate hardcopy on the filesystem by calling savefig:: diff --git a/examples/misc/agg_buffer.py b/examples/misc/agg_buffer.py index aa76efe291dc..096c7e856115 100644 --- a/examples/misc/agg_buffer.py +++ b/examples/misc/agg_buffer.py @@ -9,14 +9,8 @@ import numpy as np -import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg - - -try: - from PIL import Image -except ImportError: - raise SystemExit("Pillow must be installed to run this example") +import matplotlib.pyplot as plt plt.plot([1, 2, 3]) @@ -24,19 +18,14 @@ agg = canvas.switch_backends(FigureCanvasAgg) agg.draw() -s = agg.tostring_rgb() - -# get the width and the height to resize the matrix -l, b, w, h = agg.figure.bbox.bounds -w, h = int(w), int(h) +s, (width, height) = agg.print_to_buffer() -X = np.fromstring(s, np.uint8).reshape((h, w, 3)) +# Convert to a NumPy array. +X = np.fromstring(s, np.uint8).reshape((height, width, 4)) -try: - im = Image.fromstring("RGB", (w, h), s) -except Exception: - im = Image.frombytes("RGB", (w, h), s) +# Pass off to PIL. +from PIL import Image +im = Image.frombytes("RGBA", (width, height), s) -# Uncomment this line to display the image using ImageMagick's -# `display` tool. +# Uncomment this line to display the image using ImageMagick's `display` tool. # im.show() diff --git a/examples/misc/agg_oo_sgskip.py b/examples/misc/agg_oo_sgskip.py deleted file mode 100644 index 9f51c22815d5..000000000000 --- a/examples/misc/agg_oo_sgskip.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -============================= -The object-oriented interface -============================= - -A pure object-oriented example using the agg backend. Notice that there is no -``pyplot`` used here. -""" - -from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas -from matplotlib.figure import Figure - -fig = Figure() -# A canvas must be manually attached to the figure (pyplot would automatically -# do it). This is done by instantiating the canvas with the figure as -# argument. -FigureCanvas(fig) -ax = fig.add_subplot(111) -ax.plot([1, 2, 3]) -ax.set_title('hi mom') -ax.grid(True) -ax.set_xlabel('time') -ax.set_ylabel('volts') -fig.savefig('test') - -############################################################################# -# -# ------------ -# -# References -# """""""""" -# -# The use of the following functions, methods, classes and modules is shown -# in this example: - -import matplotlib -matplotlib.backends.backend_agg.FigureCanvasAgg -matplotlib.figure.Figure -matplotlib.figure.Figure.add_subplot -matplotlib.figure.Figure.savefig -matplotlib.axes.Axes.plot -matplotlib.axes.Axes.set_title -matplotlib.axes.Axes.grid -matplotlib.axes.Axes.set_xlabel -matplotlib.axes.Axes.set_ylabel diff --git a/examples/misc/webapp_demo_sgskip.py b/examples/misc/webapp_demo_sgskip.py deleted file mode 100644 index 8a67dfb2af93..000000000000 --- a/examples/misc/webapp_demo_sgskip.py +++ /dev/null @@ -1,64 +0,0 @@ -""" -=========== -Webapp Demo -=========== - -This example shows how to use the agg backend directly to create -images, which may be of use to web application developers who want -full control over their code without using the pyplot interface to -manage figures, figure closing etc. - -.. note:: - - It is not necessary to avoid using the pyplot interface in order to - create figures without a graphical front-end - simply setting - the backend to "Agg" would be sufficient. - -It is also worth noting that, because matplotlib can save figures to file-like -object, matplotlib can also be used inside a cgi-script *without* needing to -write a figure to disk. - -""" - -from matplotlib.backends.backend_agg import FigureCanvasAgg -from matplotlib.figure import Figure -import numpy as np - -# Fixing random state for reproducibility -np.random.seed(19680801) - - -def make_fig(): - """ - Make a figure and save it to "webagg.png". - - """ - fig = Figure() - ax = fig.add_subplot(1, 1, 1) - - ax.plot([1, 2, 3], 'ro--', markersize=12, markerfacecolor='g') - - # make a translucent scatter collection - x = np.random.rand(100) - y = np.random.rand(100) - area = np.pi * (10 * np.random.rand(100)) ** 2 # 0 to 10 point radii - c = ax.scatter(x, y, area) - c.set_alpha(0.5) - - # add some text decoration - ax.set_title('My first image') - ax.set_ylabel('Some numbers') - ax.set_xticks((.2, .4, .6, .8)) - labels = ax.set_xticklabels(('Bill', 'Fred', 'Ted', 'Ed')) - - # To set object properties, you can either iterate over the - # objects manually, or define you own set command, as in setapi - # above. - for label in labels: - label.set_rotation(45) - label.set_fontsize(12) - - FigureCanvasAgg(fig).print_png('webapp.png', dpi=150) - - -make_fig() diff --git a/examples/user_interfaces/canvasagg.py b/examples/user_interfaces/canvasagg.py new file mode 100644 index 000000000000..81999d4856c3 --- /dev/null +++ b/examples/user_interfaces/canvasagg.py @@ -0,0 +1,69 @@ +""" +============== +CanvasAgg demo +============== + +This example shows how to use the agg backend directly to create images, which +may be of use to web application developers who want full control over their +code without using the pyplot interface to manage figures, figure closing etc. + +.. note:: + + It is not necessary to avoid using the pyplot interface in order to + create figures without a graphical front-end - simply setting + the backend to "Agg" would be sufficient. + +In this example, we show how to save the contents of the agg canvas to a file, +and how to extract them to a string, which can in turn be passed off to PIL or +put in a numpy array. The latter functionality allows e.g. to use Matplotlib +inside a cgi-script *without* needing to write a figure to disk. +""" + +from matplotlib.backends.backend_agg import FigureCanvasAgg +from matplotlib.figure import Figure +import numpy as np + +fig = Figure(figsize=(5, 4), dpi=100) +# A canvas must be manually attached to the figure (pyplot would automatically +# do it). This is done by instantiating the canvas with the figure as +# argument. +canvas = FigureCanvasAgg(fig) + +# Do some plotting. +ax = fig.add_subplot(111) +ax.plot([1, 2, 3]) + +# Option 1: Save the figure to a file; can also be a file-like object (BytesIO, +# etc.). +fig.savefig("test.png") + +# Option 2: Save the figure to a string. +canvas.draw() +s, (width, height) = canvas.print_to_buffer() + +# Option 2a: Convert to a NumPy array. +X = np.fromstring(s, np.uint8).reshape((height, width, 4)) + +# Option 2b: Pass off to PIL. +from PIL import Image +im = Image.frombytes("RGBA", (width, height), s) + +# Uncomment this line to display the image using ImageMagick's `display` tool. +# im.show() + +############################################################################# +# +# ------------ +# +# References +# """""""""" +# +# The use of the following functions, methods, classes and modules is shown +# in this example: + +import matplotlib +matplotlib.backends.backend_agg.FigureCanvasAgg +matplotlib.figure.Figure +matplotlib.figure.Figure.add_subplot +matplotlib.figure.Figure.savefig +matplotlib.axes.Axes.plot diff --git a/examples/user_interfaces/histogram_demo_canvasagg_sgskip.py b/examples/user_interfaces/histogram_demo_canvasagg_sgskip.py deleted file mode 100644 index 1757a1245b5f..000000000000 --- a/examples/user_interfaces/histogram_demo_canvasagg_sgskip.py +++ /dev/null @@ -1,60 +0,0 @@ -""" -======================== -Histogram Demo CanvasAgg -======================== - -This is an example that shows you how to work directly with the agg -figure canvas to create a figure using the pythonic API. - -In this example, the contents of the agg canvas are extracted to a -string, which can in turn be passed off to PIL or put in a numeric -array - - -""" -from matplotlib.backends.backend_agg import FigureCanvasAgg -from matplotlib.figure import Figure -import numpy as np - -fig = Figure(figsize=(5, 4), dpi=100) -ax = fig.add_subplot(111) - -canvas = FigureCanvasAgg(fig) - -mu, sigma = 100, 15 -x = mu + sigma * np.random.randn(10000) - -# the histogram of the data -n, bins, patches = ax.hist(x, 50, density=True) - -# add a 'best fit' line -y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * - np.exp(-0.5 * (1 / sigma * (bins - mu))**2)) -line, = ax.plot(bins, y, 'r--') -line.set_linewidth(1) - -ax.set_xlabel('Smarts') -ax.set_ylabel('Probability') -ax.set_title(r'$\mathrm{Histogram of IQ: }\mu=100, \sigma=15$') - -ax.set_xlim((40, 160)) -ax.set_ylim((0, 0.03)) - -canvas.draw() - -s = canvas.tostring_rgb() # save this and convert to bitmap as needed - -# Get the figure dimensions for creating bitmaps or NumPy arrays, -# etc. -l, b, w, h = fig.bbox.bounds -w, h = int(w), int(h) - -if 0: - # Convert to a NumPy array - X = np.fromstring(s, np.uint8).reshape((h, w, 3)) - -if 0: - # pass off to PIL - from PIL import Image - im = Image.fromstring("RGB", (w, h), s) - im.show()