|
123 | 123 | # The Matplotlib community suggests using `IPython <https://ipython.org/>`_
|
124 | 124 | # through `Jupyter <https://jupyter.org/index.html>`_ as the primary
|
125 | 125 | # interactive environment.
|
126 |
| - |
127 |
| -############################################################################## |
128 | 126 | #
|
129 | 127 | # Plotting
|
130 | 128 | # ========
|
|
135 | 133 | # code.
|
136 | 134 |
|
137 | 135 | import matplotlib.pyplot as plt
|
| 136 | +import numpy as np |
138 | 137 |
|
139 | 138 | ##############################################################################
|
140 | 139 | #
|
141 | 140 | # The ``pyplot`` module in Matplotlib is a collection of functions. The
|
142 | 141 | # module's functions create, manage, and manipulate the current Figure and the
|
143 | 142 | # plotting area.
|
144 | 143 | #
|
| 144 | +# NumPy is a common scientific Python library that benefits users with |
| 145 | +# additional robust tools for manipulating data. |
| 146 | +# |
145 | 147 | # Two Approaches for Creating Graphs
|
146 | 148 | # ----------------------------------
|
147 | 149 | #
|
|
228 | 230 |
|
229 | 231 | fig, ax = plt.subplots()
|
230 | 232 | # Explicit Figure & Axes unpacked separately with module.
|
| 233 | +# Conventional object abbreviations are `fig` and `ax`, respectively. |
231 | 234 |
|
232 | 235 | ax.plot(x, y1, label='Checking Account')
|
233 | 236 | ax.plot(x, y2, label='Savings Account')
|
|
299 | 302 | # The names and spelling for methods may be similar for both explicit and
|
300 | 303 | # implicit approaches. Errors may occur when using the wrong corresponding
|
301 | 304 | # method. Confirm with the documentation API of `~.axes.Axes` for explicit
|
302 |
| -# and mod:`matplotlib.pyplot` for implicit or other respective method |
| 305 | +# and :mod:`matplotlib.pyplot` for implicit or other respective method |
303 | 306 | # names.
|
304 | 307 | #
|
305 |
| -# Customizations |
306 |
| -# ============== |
| 308 | +# Configuration |
| 309 | +# ============= |
307 | 310 | #
|
308 | 311 | # There are two main parts to building a visualization with Matplotlib, the
|
309 | 312 | # ``Figure`` and the ``Axes``.
|
|
335 | 338 | # Figure can contain multiple Axes, but each Axes is specific to one
|
336 | 339 | # Figure.
|
337 | 340 | #
|
| 341 | +# In a Figure, each Axes can contain any number of visual elements. An Axes may |
| 342 | +# have more than one type of visualization of data. From the `Plotting`_ |
| 343 | +# section above, the Axes in both explicit and implicit strategies contain |
| 344 | +# multiple types of visualizations of data on a single Axes. Each of these |
| 345 | +# types are specific to the Axes they are in. |
| 346 | +# |
338 | 347 | # Other Components
|
339 | 348 | # ^^^^^^^^^^^^^^^^
|
340 | 349 | #
|
341 | 350 | # :class:`~matplotlib.artist.Artist`
|
342 | 351 | #
|
343 |
| -# Artists are the visible elements when the Figure is rendered. They |
344 |
| -# correspond to a specific Axes and cannot be shared or transferred. |
| 352 | +# Artists are broad Matplotlib objects that display visuals. These are the |
| 353 | +# visible elements when the Figure is rendered. They correspond to a specific |
| 354 | +# Axes and cannot be shared or transferred. In Matplotlib programming, all |
| 355 | +# objects for display are Artists. |
345 | 356 | #
|
346 | 357 | # .. note::
|
347 | 358 | #
|
348 | 359 | # Axes and Axis are not synonymous. Axis refers to
|
349 | 360 | # :class:`~matplotlib.axis.Axis`.
|
350 | 361 | #
|
| 362 | +# Manipulating Artists |
| 363 | +# -------------------- |
| 364 | +# |
| 365 | +# With simple plots, Matplotlib automatically generates the basic elements of |
| 366 | +# a graph. Artists as objects allow for more control over the visual. |
| 367 | +# |
| 368 | +# Matplotlib generates additional visual elements as Artists in the form of |
| 369 | +# objects. As Artists, each has its own respective methods and functions. |
| 370 | +# Explicit and implicit approaches use different methods and are not |
| 371 | +# interchangeable. |
| 372 | +# |
| 373 | +# The table below compares common Artists and their different methods. |
| 374 | +# |
| 375 | +# +-----------------------+--------------------------+------------------------+ |
| 376 | +# | Artist | Explicit | Implicit | |
| 377 | +# +=======================+==========================+========================+ |
| 378 | +# | Visible elements from | Each specific Axes has | The ``pyplot`` module | |
| 379 | +# | rendered Figure. | its own method for | manages Artists based | |
| 380 | +# | | artists. | on most recent Figure | |
| 381 | +# | | | or Axes. | |
| 382 | +# +-----------------------+--------------------------+------------------------+ |
| 383 | +# | X-axis labels | ``ax.set_xticks()`` | ``plt.xlabel()`` | |
| 384 | +# | | ``ax.set_xticklabels()`` | | |
| 385 | +# +-----------------------+--------------------------+------------------------+ |
| 386 | +# | Y-axis labels | ``x.set_yticks()`` | ``plt.ylabel()` | |
| 387 | +# | | ``ax.set_yticklabels()`` | | |
| 388 | +# +-----------------------+--------------------------+------------------------+ |
| 389 | +# | Title (Axes) | ``ax.set_title()`` | ``plt.title()`` | |
| 390 | +# +-----------------------+--------------------------+------------------------+ |
| 391 | +# | Legend (Axes) | ``ax.legend()`` | ``plt.legend()`` | |
| 392 | +# +-----------------------+--------------------------+------------------------+ |
| 393 | +# |
| 394 | +# .. note:: |
| 395 | +# |
| 396 | +# In explicit programming, ``ax`` refers to an assigned variable for a |
| 397 | +# specific Axes. Also, axis labels require separate setting actions for |
| 398 | +# each specific Axes. |
| 399 | +# |
| 400 | +# In implicit programming, the ``pyplot`` module automatically manages |
| 401 | +# separate setting actions for state-based Matplotlib objects. |
| 402 | +# |
| 403 | +# |
| 404 | +# Pie Chart Examples |
| 405 | +# ------------------ |
| 406 | +# |
| 407 | +# Matplotlib pie charts create wedges based on data and manipulate the size of |
| 408 | +# the Artists based on the ratio of the slice to the sum of the data. The |
| 409 | +# ``.pie()`` method is similar for both explicit and implicit approaches. |
| 410 | +# |
| 411 | +# The code below illustrates various levels of configuration in keyword |
| 412 | +# arguments as well as Artist methods for both explicit and implicit |
| 413 | +# programming. |
| 414 | +# |
| 415 | +# See `matplotlib.axes.Axes.pie` and `matplotlib.pyplot.pie` for more |
| 416 | +# information about the APIs for explicit and implicit, respectively. |
| 417 | + |
| 418 | +# Data |
| 419 | + |
| 420 | +budget = [475, 300, 125, 50] |
| 421 | +# Data points are represented in wedge size compared to total sum. |
| 422 | + |
| 423 | +descriptions = ['Shared house in Philadelphia', |
| 424 | + 'Dog costs, phone, utilities', |
| 425 | + 'Groceries & takeout', |
| 426 | + 'Treasury bonds'] |
| 427 | +categories = ['Rent', 'Bills', 'Food', 'Savings'] |
| 428 | +# These lists of strings contribute to labeling corresponding to data. |
| 429 | + |
| 430 | +colors = ['#1f77b4', '#ff7f0e', '#d62728', '#2ca02c'] |
| 431 | +# Hex color codes determine respective wedge color. |
| 432 | + |
| 433 | +explode = [0, 0.1, 0.15, 0.35] |
| 434 | +# Float list represents percentage of radius to separate from center. |
| 435 | + |
| 436 | + |
| 437 | +def autopct_format(percent, group): |
| 438 | + """ |
| 439 | + Takes percent equivalent and calculates original value from data. |
| 440 | + Returns fstring of value above percentage. |
| 441 | + """ |
| 442 | + value = int(percent/100.*np.sum(group)) |
| 443 | + return f'${value:<4}\n{percent:1.1f}%' |
| 444 | +# This function is used as a lambda for formatting labels in wedges. |
| 445 | + |
| 446 | +############################################################################## |
| 447 | +# |
| 448 | +# The following two plots are identical. Both the explicit and implicit |
| 449 | +# approaches generate the exact same plot when using the same variables. |
| 450 | +# |
| 451 | +# Basic |
| 452 | +# ^^^^^ |
| 453 | + |
| 454 | +# Explicit |
| 455 | + |
| 456 | + |
| 457 | +fig, ax = plt.subplots() |
| 458 | + |
| 459 | +ax.pie(budget, colors=colors, labels=categories) |
| 460 | +ax.legend() |
| 461 | +ax.set_title('Average Monthly Income Expenses') |
| 462 | +ax.axis('equal') |
| 463 | + |
| 464 | +plt.show() |
| 465 | + |
| 466 | +############################################################################## |
| 467 | +# |
| 468 | +# |
| 469 | + |
| 470 | +plt.pie(budget, colors=colors, labels=categories) |
| 471 | +plt.legend() |
| 472 | +plt.axis('equal') |
| 473 | +plt.title('Average Monthly Income Expenses') |
| 474 | +plt.show() |
| 475 | + |
| 476 | +############################################################################## |
| 477 | +# |
| 478 | +# .. note:: |
| 479 | +# |
| 480 | +# There are minor differences in the method names. Overall, each method |
| 481 | +# performs the same action through the different approaches. |
| 482 | +# |
| 483 | +# Additional Configurations |
| 484 | +# ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 485 | +# |
| 486 | +# Many methods contain optional keyword arguments for further configuration. |
| 487 | +# In the explicit example below, there are values and functions in keyword |
| 488 | +# arguments that format the Artists. |
| 489 | + |
| 490 | +fig, ax = plt.subplots() |
| 491 | + |
| 492 | +ax.pie(budget, |
| 493 | + colors=colors, |
| 494 | + explode=explode, |
| 495 | + labels=categories, |
| 496 | + autopct=lambda pct: autopct_format(pct, budget), |
| 497 | + startangle=-80, |
| 498 | + shadow=True) |
| 499 | + |
| 500 | + |
| 501 | +ax.legend() |
| 502 | +ax.axis('equal') |
| 503 | +ax.set_title('Average Monthly Income Expenses') |
| 504 | +plt.show() |
| 505 | + |
| 506 | +############################################################################## |
| 507 | +# |
| 508 | +# |
| 509 | + |
| 510 | +fig, ax = plt.subplots() |
| 511 | + |
| 512 | +wedges, texts, autotexts = ax.pie(budget, labels=descriptions, |
| 513 | + colors=colors, explode=explode, |
| 514 | + autopct='%d', startangle=45, |
| 515 | + pctdistance=0.85, labeldistance=1.125, |
| 516 | + wedgeprops=dict(width=0.3), |
| 517 | + shadow=True) |
| 518 | + |
| 519 | +for text, value in zip(autotexts, budget): |
| 520 | + text.set_text(f'${value}\n{text.get_text()}%') |
| 521 | + text.set_fontweight('medium') |
| 522 | + |
| 523 | +ax.legend(wedges, categories, title='Categories', |
| 524 | + bbox_to_anchor=(0.125, 0.5), loc='center right') |
| 525 | +ax.set_title('Average Monthly Income Expenses') |
| 526 | +ax.axis('equal') |
| 527 | + |
| 528 | +plt.show() |
| 529 | + |
| 530 | +############################################################################## |
| 531 | +# |
| 532 | +# |
| 533 | +# Customization |
| 534 | +# ============= |
351 | 535 | #
|
352 | 536 | # Multiple Graphs within a Figure
|
353 | 537 | # -------------------------------
|
|
0 commit comments