105
105
#
106
106
# In order to install Matplotlib from the source directory, run the
107
107
# following command line executions using Python and installer program ``pip``
108
- # for the latest version of Matplotlib and its dependencies. This will compile
108
+ # for the latest version of Matplotlib and its dependencies. This compiles
109
109
# the library from the current directory on your machine. Depending on your
110
110
# operating system, you may need additional support.
111
111
#
172
172
# The Matplotlib community does not recommend interchanging explicit and
173
173
# implicit strategies. When using one as standard, all code should follow
174
174
# the same strategy. Switching back and forth between explicit and
175
- # implicit programming can yield errors.
175
+ # implicit programming may yield errors.
176
176
#
177
177
# For other techniques of creating plots with Matplotlib, refer to
178
178
# :ref:`user_interfaces`.
251
251
# For the OOP example, the Figure and Axes are unpacked from the module using
252
252
# a single instance of ``pyplot``. This convention uses ``plt.subplots()``
253
253
# and defaults to one Figure, ``fig``, and one Axes, ``ax``. The
254
- # `Customizations `_ section below contains additional information about
255
- # multiple visulizations and other modifications.
254
+ # `Configuration `_ section below contains additional information about
255
+ # manipulating visuals, multiple visulizations, and other modifications.
256
256
#
257
257
# Using the OOP approach allows for ``fig`` and ``ax`` to use separate methods
258
258
# to manipulate the visualization. Instead of using the module ``pyplot`` for
316
316
#
317
317
# The image below depicts each visible element of a Matplotlib graph. The
318
318
# graphic uses Matplotlib to display and highlight each individual part of the
319
- # visualization. The source code is available as
320
- # :ref:`sphx_glr_gallery_showcase_anatomy.py`.
319
+ # visualization. To see how the programming operates, the source code is
320
+ # available at :ref:`sphx_glr_gallery_showcase_anatomy.py`.
321
321
#
322
322
# .. note::
323
323
#
363
363
# --------------------
364
364
#
365
365
# With simple plots, Matplotlib automatically generates the basic elements of
366
- # a graph. Artists as objects allow for more control over the visual.
366
+ # a graph. For more control over the visual, use Artists and its methods .
367
367
#
368
368
# Matplotlib generates additional visual elements as Artists in the form of
369
369
# objects. As Artists, each has its own respective methods and functions.
383
383
# | X-axis labels | ``ax.set_xticks()`` | ``plt.xlabel()`` |
384
384
# | | ``ax.set_xticklabels()`` | |
385
385
# +-----------------------+--------------------------+------------------------+
386
- # | Y-axis labels | ``x .set_yticks()`` | ``plt.ylabel()` |
386
+ # | Y-axis labels | ``ax .set_yticks()`` | ``plt.ylabel()`` |
387
387
# | | ``ax.set_yticklabels()`` | |
388
388
# +-----------------------+--------------------------+------------------------+
389
389
# | Title (Axes) | ``ax.set_title()`` | ``plt.title()`` |
390
390
# +-----------------------+--------------------------+------------------------+
391
391
# | Legend (Axes) | ``ax.legend()`` | ``plt.legend()`` |
392
392
# +-----------------------+--------------------------+------------------------+
393
393
#
394
- # .. note::
394
+ # The term ``ax`` refers to an assigned variable for a specific Axes. Using
395
+ # explicit programming requires additional tasks of setting objects prior to
396
+ # assigning labels. Whereas with implicit programming, the module manages
397
+ # those tasks without specification.
395
398
#
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
+ # For additional information about available methods, see the table below.
399
400
#
400
- # In implicit programming, the ``pyplot`` module automatically manages
401
- # separate setting actions for state-based Matplotlib objects.
401
+ # +------------------------------------+------------------------------------+
402
+ # | Explicit | :class:`matplotlib.axes.Axes` |
403
+ # +------------------------------------+------------------------------------+
404
+ # | Implicit | :mod:`matplotlib.pyplot` |
405
+ # +------------------------------------+------------------------------------+
402
406
#
403
407
#
404
408
# Pie Chart Examples
412
416
# arguments as well as Artist methods for both explicit and implicit
413
417
# programming.
414
418
#
415
- # See `matplotlib.axes.Axes.pie` and `matplotlib.pyplot.pie` for more
416
- # information about the APIs for explicit and implicit, respectively.
417
419
418
420
# Data
419
421
420
422
budget = [475 , 300 , 125 , 50 ]
421
423
# Data points are represented in wedge size compared to total sum.
424
+ # Matplotlib methods calculate these values automatically based on input.
422
425
423
- descriptions = ['Shared house in Philadelphia' ,
424
- 'Dog costs, phone, utilities ' ,
425
- 'Groceries & takeout' ,
426
+ descriptions = ['Shared house\n in Philadelphia' ,
427
+ 'Dog costs, phone,\n utilities ' ,
428
+ 'Groceries\n & takeout' ,
426
429
'Treasury bonds' ]
427
430
categories = ['Rent' , 'Bills' , 'Food' , 'Savings' ]
428
- # These lists of strings contribute to labeling corresponding to data.
431
+ # These lists of strings contribute to labeling corresponding data.
429
432
430
433
colors = ['#1f77b4' , '#ff7f0e' , '#d62728' , '#2ca02c' ]
431
434
# Hex color codes determine respective wedge color.
432
435
433
436
explode = [0 , 0.1 , 0.15 , 0.35 ]
434
- # Float list represents percentage of radius to separate from center.
437
+ # List of floats represents percentage of radius to separate from center.
435
438
436
439
437
440
def autopct_format (percent , group ):
438
441
"""
439
442
Takes percent equivalent and calculates original value from data.
440
- Returns fstring of value above percentage.
443
+ Returns fstring of value new line above percentage.
441
444
"""
442
445
value = int (percent / 100. * np .sum (group ))
443
446
return f'${ value :<4} \n { percent :1.1f} %'
444
447
# This function is used as a lambda for formatting labels in wedges.
445
448
446
449
##############################################################################
447
450
#
451
+ # Basic
452
+ # ^^^^^
453
+ #
448
454
# The following two plots are identical. Both the explicit and implicit
449
455
# approaches generate the exact same plot when using the same variables.
450
456
#
451
- # Basic
452
- # ^^^^^
457
+ # See `matplotlib.axes.Axes.pie` and `matplotlib.pyplot.pie` for more
458
+ # information about the APIs for explicit and implicit, respectively.
453
459
454
460
# Explicit
455
461
@@ -460,6 +466,7 @@ def autopct_format(percent, group):
460
466
ax .legend ()
461
467
ax .set_title ('Average Monthly Income Expenses' )
462
468
ax .axis ('equal' )
469
+ # The axis method sets the aspect ratio of the visual as equal.
463
470
464
471
plt .show ()
465
472
@@ -469,8 +476,10 @@ def autopct_format(percent, group):
469
476
470
477
plt .pie (budget , colors = colors , labels = categories )
471
478
plt .legend ()
472
- plt .axis ('equal' )
473
479
plt .title ('Average Monthly Income Expenses' )
480
+ plt .axis ('equal' )
481
+ # The pyplot module contains an identical method for aspect ratio setting.
482
+
474
483
plt .show ()
475
484
476
485
##############################################################################
@@ -480,58 +489,123 @@ def autopct_format(percent, group):
480
489
# There are minor differences in the method names. Overall, each method
481
490
# performs the same action through the different approaches.
482
491
#
483
- # Additional Configurations
484
- # ^^^^^^^^^^^^^^^^^^^^^^^^^
492
+ # These pie charts are simple in that there is not much distinguishing
493
+ # information. Keyword arguments and Artists add the ability to implement
494
+ # more ways of displaying content.
495
+ #
496
+ # Additional Customization
497
+ # ^^^^^^^^^^^^^^^^^^^^^^^^
485
498
#
486
499
# 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.
500
+ # In the examples for explicit programming below, there are values and
501
+ # functions in keyword arguments that format the Artists. These changes also
502
+ # apply to implicit programming, though with varying method names.
503
+ #
504
+ # The pie chart below adds configurations with keyword arguments for
505
+ # ``explode``, ``autopct``, ``startangle``, and ``shadow``. These keyword
506
+ # arguments help to manipulate the Artists.
507
+
508
+ # Explicit
489
509
490
510
fig , ax = plt .subplots ()
491
511
492
512
ax .pie (budget ,
493
513
colors = colors ,
494
- explode = explode ,
495
514
labels = categories ,
496
- autopct = lambda pct : autopct_format (pct , budget ),
515
+ explode = explode ,
516
+ # The explode keyword argument uses the explode variable from data to
517
+ # separate respective wedges from the center.
518
+ autopct = '%1.1f%%' ,
519
+ # The autopct keyword argument takes formatting strings and functions
520
+ # to generate text within the wedge. '%1.1f%%' uses string formatters.
497
521
startangle = - 80 ,
498
- shadow = True )
499
-
522
+ # The startangle keyword argument changes where the first wedge spans.
523
+ # Angles start at 0 degrees on the X-axis and move counterclockwise.
524
+ shadow = True
525
+ # The shadow keyword argument toggles a shadow on the visual.
526
+ )
500
527
501
528
ax .legend ()
502
- ax .axis ('equal' )
503
529
ax .set_title ('Average Monthly Income Expenses' )
530
+ ax .axis ('equal' )
531
+
504
532
plt .show ()
505
533
506
534
##############################################################################
507
535
#
508
- #
536
+ # In the pie chart below, there are additional keyword arguments to further
537
+ # customize the visual. Also, the ``legend`` as an Artist has parameters that
538
+ # enable more specification for the information displayed. For more, see the
539
+ # :ref:`legend-guide`
509
540
510
- fig , ax = plt . subplots ()
541
+ # Explicit
511
542
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 )
543
+ fig , ax = plt .subplots ()
518
544
519
- for text , value in zip (autotexts , budget ):
520
- text .set_text (f'${ value } \n { text .get_text ()} %' )
521
- text .set_fontweight ('medium' )
545
+ budget_pie = ax .pie (budget ,
546
+ colors = colors ,
547
+ labels = descriptions ,
548
+ # Instead of using the categories data as a label, the
549
+ # descriptions act as text to label the wedges. This aids
550
+ # in removing redundant information from the previous
551
+ # pie chart.
552
+ explode = explode ,
553
+ autopct = lambda pct : autopct_format (pct , budget ),
554
+ # The autopct keyword argument in this instance uses a
555
+ # function in a lambda to return a formatted string.
556
+ startangle = 45 ,
557
+ pctdistance = 0.85 ,
558
+ # The pctdistance keyword argument places the autopct
559
+ # Artist at a location using the float as a percentage of
560
+ # the radius.
561
+ labeldistance = 1.125 ,
562
+ # The labeldistance keyword argument specifies the float as
563
+ # a percentage of the radius to place labels.
564
+ wedgeprops = dict (width = 0.3 ),
565
+ # The wedgeprops keyword argument can also take
566
+ # dictionaries to pass on to the artists. In this
567
+ # instance, the float for width sets the wedge size as a
568
+ # percentage of the radius starting from the outer edge.
569
+ shadow = True )
570
+
571
+ wedges , texts , autotexts = budget_pie
572
+ # The pie() method unpacks into three objects, wedges, texts, and autotexts.
573
+ # These Artists have their own methods for addtional customization.
574
+
575
+ ax .legend (wedges ,
576
+ # The wedges variable unpacked from the method serve as the handles
577
+ # for the legend.
578
+ categories ,
579
+ # The information from the data categories correspond to each
580
+ # respective wedge instead of redundant labeling from the previous
581
+ # pie chart.
582
+ title = 'Categories' ,
583
+ # The legend has a title keyword argument.
584
+ bbox_to_anchor = (0.125 , 0.5 ),
585
+ # This keyword argument in conjunction with loc places the legend
586
+ # at a specific point. The tuple floats are coordinates for the
587
+ # Figure.
588
+ loc = 'center right'
589
+ # The loc keyword argument works in conjunction with bbox_to_anchor
590
+ # and in this instance, determines the part of the legend for
591
+ # placement. Without bbox_to_anchor, Matplotlib automatically
592
+ # manages coordinates in relation to specifications of the
593
+ # parameters of loc.
594
+ )
522
595
523
- ax .legend (wedges , categories , title = 'Categories' ,
524
- bbox_to_anchor = (0.125 , 0.5 ), loc = 'center right' )
525
596
ax .set_title ('Average Monthly Income Expenses' )
526
597
ax .axis ('equal' )
527
598
599
+ fig .tight_layout ()
600
+ # The Figure method tight_layout() manages the space between all Artists to
601
+ # maximize visiblity on the Figure. This method also contains various
602
+ # parameters for configuration.
603
+
528
604
plt .show ()
529
605
530
606
##############################################################################
531
607
#
532
608
#
533
- # Customization
534
- # =============
535
609
#
536
610
# Multiple Graphs within a Figure
537
611
# -------------------------------
0 commit comments