21
21
# The library is accessible through a variety of operating systems and
22
22
# programming environments. The fundamental ideas behind Matplotlib for
23
23
# visualizations involve taking data and transforming it through functions and
24
- # methods. This process occurs on the backend and is not user-facing. For more
25
- # information regarding manipulating backend capabilities, see
26
- # :ref:`backends`.
24
+ # methods. This process occurs internally and is not user-facing.
27
25
#
28
26
# There are two main ways of producing graphs with Matplotlib, explicit and
29
27
# implicit. Explicit code, using Object Oriented Programming (OOP), and
57
55
#
58
56
# Implicit programming with ``pyplot`` is simpler. It is helpful for basic
59
57
# plots and for interactive environments, such as Jupyter Notebooks. Users
60
- # familiar with MATLAB or would like to have Matplotlib automatically create
61
- # and manage parts of the visualization benefit from using the ``pyplot``
62
- # module to graph data. Using implicit programming acts as a convenient
63
- # shortcut for generating visualizations. New users to Matplotlib may
64
- # experience difficulty understanding how elements of a visualization work
65
- # together when using the implicit approach.
58
+ # familiar with MATLAB or wish to have Matplotlib create and manage parts of
59
+ # the visualization in state-based programming benefit from using ``pyplot``.
60
+ # Using implicit programming acts as a convenient shortcut for generating
61
+ # visualizations. New users to Matplotlib may experience difficulty
62
+ # understanding how elements of a visualization work together when using the
63
+ # implicit approach.
66
64
#
67
65
# Examples
68
66
# --------
240
238
241
239
# Explicit programming with OOP
242
240
241
+ # Assigning sample data to labeled variables.
243
242
x = months
244
243
y1 = income
245
244
y2 = chk_acct_09
246
245
y3 = svg_acct_09
247
246
y4 = chk_acct_10
248
247
y5 = svg_acct_10
249
- # Assigning sample data to labeled variables.
250
248
251
- fig , ax = plt .subplots ()
252
249
# Explicit Figure & Axes unpacked separately with module.
253
250
# Conventional object abbreviations are `fig` and `ax`, respectively.
251
+ fig , ax = plt .subplots ()
254
252
253
+ # Single explicit Axes graphs multiple data points.
255
254
ax .plot (x , y1 , label = 'Income' )
256
255
ax .plot (x , y2 , label = 'Checking Account' )
257
256
ax .plot (x , y3 , label = 'Savings Account' )
258
- # Single explicit Axes graphs multiple data points.
259
257
258
+ # Explicit Axes use separate methods to manage parts of Figure.
260
259
ax .set_xlabel ('Month' )
261
260
ax .set_ylabel ('USD' )
262
261
ax .set_title ('Personal Financial Tracking from 2009' )
263
262
ax .legend ()
264
- # Explicit Axes use separate methods to manage parts of Figure.
265
263
266
- plt .show ()
267
264
# The pyplot module displays the Figure.
265
+ plt .show ()
268
266
269
267
##############################################################################
270
268
#
293
291
294
292
# Previous variables are still referenced.
295
293
294
+ # Module plots multiple data points on implicitly generated Axes.
296
295
plt .plot (x , y1 , label = 'Income' )
297
296
plt .plot (x , y2 , label = 'Checking Account' )
298
297
plt .plot (x , y3 , label = 'Savings Account' )
299
- # Module plots multiple data points on implicitly generated Axes.
300
298
299
+ # Module methods generate parts of Figure.
301
300
plt .xlabel ('Month' )
302
301
plt .ylabel ('USD' )
303
302
plt .title ("Personal Financial Tracking from 2009" )
304
303
plt .legend ()
305
- # Module methods generate parts of Figure.
306
304
307
- plt .show ()
308
305
# The module displays the Figure.
306
+ plt .show ()
309
307
310
308
##############################################################################
311
309
#
350
348
# without assigned data.
351
349
#
352
350
353
- fig , ax = plt .subplots ()
354
351
# Explicit Figure and Axes unpacked from module function.
355
352
# No data transformed for visualizations.
356
- plt .show ()
353
+ fig , ax = plt .subplots ()
354
+
357
355
# Module displays empty Figure and Axes.
356
+ plt .show ()
358
357
359
358
##############################################################################
360
359
#
497
496
498
497
# Sample data for monthly spending averages.
499
498
500
- budget = [475 , 300 , 125 , 50 ]
501
499
# Data points correspond to wedge size as a ratio of total sum.
502
500
# Matplotlib methods calculate these values automatically based on input.
501
+ budget = [475 , 300 , 125 , 50 ]
503
502
503
+ # Lists of strings contribute to labeling corresponding data.
504
504
descriptions = ['Shared house\n in Philadelphia' ,
505
505
'Dog costs, phone,\n utilities' ,
506
506
'Groceries\n & takeout' ,
507
507
'Treasury bonds' ]
508
508
categories = ['Rent' , 'Bills' , 'Food' , 'Savings' ]
509
- # Lists of strings contribute to labeling corresponding data.
510
509
511
- colors = ['#1f77b4' , '#ff7f0e' , '#d62728' , '#2ca02c' ]
512
510
# Hex color codes determine respective wedge color.
511
+ colors = ['#1f77b4' , '#ff7f0e' , '#d62728' , '#2ca02c' ]
513
512
514
- explode = [0 , 0.1 , 0.15 , 0.35 ]
515
513
# List of floats represents percentage of radius to separate from center.
514
+ explode = [0 , 0.1 , 0.15 , 0.35 ]
515
+
516
+ # This function operates in conjunction with the functools partial function
517
+ # for formatting labels in wedges.
516
518
517
519
518
520
def autopct_format (percent , group ):
@@ -535,8 +537,7 @@ def autopct_format(percent, group):
535
537
value = int (percent / 100. * np .sum (group ))
536
538
formatted = f'${ value :<4} \n { percent :1.1f} %'
537
539
return formatted
538
- # This function operates in conjunction with the functools partial function
539
- # for formatting labels in wedges.
540
+
540
541
541
542
##############################################################################
542
543
#
@@ -557,8 +558,7 @@ def autopct_format(percent, group):
557
558
ax .pie (budget , colors = colors , labels = categories )
558
559
ax .legend ()
559
560
ax .set_title ('Average Monthly Income Expenses' )
560
- ax .axis ('equal' )
561
- # The axis method sets the aspect ratio of the visual as equal.
561
+ ax .axis ('equal' ) # The axis method sets the aspect ratio as equal.
562
562
563
563
plt .show ()
564
564
@@ -569,8 +569,7 @@ def autopct_format(percent, group):
569
569
plt .pie (budget , colors = colors , labels = categories )
570
570
plt .legend ()
571
571
plt .title ('Average Monthly Income Expenses' )
572
- plt .axis ('equal' )
573
- # The pyplot module contains an identical method for setting aspect ratio.
572
+ plt .axis ('equal' ) # The pyplot module has identical method for aspect ratio.
574
573
575
574
plt .show ()
576
575
@@ -601,21 +600,20 @@ def autopct_format(percent, group):
601
600
602
601
fig , ax = plt .subplots ()
603
602
603
+ # The explode keyword argument uses explode variable data to separate
604
+ # respective wedges from center.
605
+ # The autopct keyword argument takes formatting strings and functions to
606
+ # generate text within wedge. '%1.1f%%' is the string formatter.
607
+ # The startangle keyword argument changes where first wedge spans. Angles start
608
+ # at 0 degrees on X-axis and move counterclockwise.
609
+ # The shadow keyword argument toggles a shadow on the visual.
604
610
ax .pie (budget ,
605
611
colors = colors ,
606
612
labels = categories ,
607
613
explode = explode ,
608
- # The explode keyword argument uses the explode variable data to
609
- # separate respective wedges from the center.
610
614
autopct = '%1.1f%%' ,
611
- # The autopct keyword argument takes formatting strings and functions
612
- # to generate text within the wedge. '%1.1f%%' is a string formatter.
613
615
startangle = - 80 ,
614
- # The startangle keyword argument changes where the first wedge spans.
615
- # Angles start at 0 degrees on the X-axis and move counterclockwise.
616
- shadow = True
617
- # The shadow keyword argument toggles a shadow on the visual.
618
- )
616
+ shadow = True )
619
617
620
618
ax .legend ()
621
619
ax .set_title ('Average Monthly Income Expenses' )
@@ -634,63 +632,54 @@ def autopct_format(percent, group):
634
632
635
633
fig , ax = plt .subplots ()
636
634
635
+ # Descriptions now act as text labels for wedges. This removes redundant
636
+ # information from previous pie chart.
637
+ # The autopct keyword argument calls a function as well. The functools partial
638
+ # function returns a formatted string. See Note below for more.
639
+ # The pctdistance keyword argument places autopct Artist at a location using
640
+ # float as percentage of radius.
641
+ # The labeldistance keyword argument specifies float as percentage of radius to
642
+ # place labels.
643
+ # The wedgeprops keyword argument also takes dictionaries to pass to Artists.
644
+ # The float for width sets wedge size as percentage of radius starting from
645
+ # outer edge.
637
646
budget_pie = ax .pie (budget ,
638
647
colors = colors ,
639
648
labels = descriptions ,
640
- # Descriptions now act as text labels for the wedges.
641
- # This removes redundant information from the previous
642
- # pie chart.
643
649
explode = explode ,
644
650
autopct = partial (autopct_format , group = budget ),
645
- # The autopct keyword argument calls a function as well.
646
- # The functools partial function returns a formatted
647
- # string. See Note below for more.
648
651
startangle = 45 ,
649
652
pctdistance = 0.85 ,
650
- # The pctdistance keyword argument places the autopct
651
- # Artist at a location using the float as a percentage of
652
- # the radius.
653
653
labeldistance = 1.125 ,
654
- # The labeldistance keyword argument specifies the float as
655
- # a percentage of the radius to place labels.
656
654
wedgeprops = dict (width = 0.3 ),
657
- # The wedgeprops keyword argument also takes dictionaries
658
- # to pass on to the Artists. The float for width sets the
659
- # wedge size as a percentage of the radius starting from
660
- # the outer edge.
661
655
shadow = True )
662
656
663
- wedges , texts , autotexts = budget_pie
664
657
# The pie() method unpacks into three Artist objects. The Artists wedges,
665
658
# texts, and autotexts have their own methods for addtional customization.
659
+ wedges , texts , autotexts = budget_pie
666
660
661
+ # The unpacked wedges variable serve as handles for legend.
662
+ # Info from categories correspond to respective wedge instead of redundant
663
+ # labeling from previous pie chart.
664
+ # Legend has title keyword argument.
665
+ # Keyword argument bbox_to_anchor with loc places legend at specific point.
666
+ # Tuple floats are coordinates for Figure as row and column of Axes.
667
+ # Keyword argument loc works with bbox_to_anchor to determine part of legend
668
+ # for placement. Without bbox_to_anchor, Matplotlib automatically manages
669
+ # coordinates in relation to parameters of loc.
667
670
ax .legend (wedges ,
668
- # The wedges variable unpacked from the method serve as the handles
669
- # for the legend.
670
671
categories ,
671
- # The information from the data categories corresponds to each
672
- # respective wedge instead of redundant labeling from the previous
673
- # pie chart.
674
672
title = 'Categories' ,
675
- # The legend has a title keyword argument.
676
673
bbox_to_anchor = (0.125 , 0.5 ),
677
- # This keyword argument in conjunction with loc places the legend
678
- # at a specific point. The tuple floats are coordinates for the
679
- # Figure in terms of row and column of Axes.
680
- loc = 'center right'
681
- # The loc keyword argument works in conjunction with bbox_to_anchor
682
- # and determines the part of the legend for placement. Without
683
- # bbox_to_anchor, Matplotlib automatically manages coordinates in
684
- # relation to specifications of the parameters of loc.
685
- )
674
+ loc = 'center right' )
686
675
687
676
ax .set_title ('Average Monthly Income Expenses' )
688
677
ax .axis ('equal' )
689
678
690
- fig .tight_layout ()
691
- # The Figure method tight_layout() manages the space between all Artists to
692
- # maximize visiblity on the Figure. This method also contains various
679
+ # The Figure method tight_layout() manages space between all Artists to
680
+ # maximize visiblity on Figure. This method also contains various
693
681
# parameters for configuration.
682
+ fig .tight_layout ()
694
683
695
684
plt .show ()
696
685
@@ -728,41 +717,41 @@ def autopct_format(percent, group):
728
717
729
718
# Explicit with OOP
730
719
720
+ # Figure and two Axes unpacked from matrix as row (1) & column (2).
721
+ # Keyword arguments provide additional details of sharing Y-Axis, Figure size
722
+ # and layout formatting.
731
723
fig , (ax1 , ax2 ) = plt .subplots (1 , 2 ,
732
724
sharey = 'row' ,
733
725
figsize = [8 , 4 ],
734
726
constrained_layout = True )
735
- # Figure and two Axes unpacked from arguments (1, 2) as row & column.
736
- # Keyword arguments provide additional details of sharing Y-Axis, Figure size
737
- # and layout formatting.
738
727
739
- fig .suptitle ('Personal Financial Tracking \' 09 - \' 10' )
740
728
# Explicit Figure object has separate method for title.
729
+ fig .suptitle ('Personal Financial Tracking \' 09 - \' 10' )
741
730
731
+ # First explicit Axes object plots data with additional keyword arguments.
742
732
ax1 .plot (x , y1 , label = 'Income' )
743
733
ax1 .plot (x , y2 , label = 'Checking' )
744
734
ax1 .plot (x , y3 , color = 'green' , label = 'Savings' )
745
- # First explicit Axes object plots data with additional keyword arguments.
746
735
736
+ # First explicit Axes object uses separate methods for ticks on X-Axis,
737
+ # title, and legend. Keyword arguments are for additional configurations.
747
738
ax1 .set_xticks (months )
748
739
ax1 .set_xticklabels (months , rotation = 270 )
749
740
ax1 .set_title ('2009' , fontsize = 'small' )
750
741
ax1 .legend (loc = 'upper left' )
751
- # First explicit Axes object uses separate methods for ticks on the X-Axis,
752
- # title, and legend. Keyword arguments are for additional configurations.
753
742
743
+ # Explicit second Axes object plots data similarly to first explicit Axes.
754
744
ax2 .plot (x , y1 , label = 'Income' )
755
745
ax2 .plot (x , y4 , label = 'Checking' )
756
746
ax2 .plot (x , y5 , color = 'green' , label = 'Savings' )
757
- # Explicit second Axes object plots data similarly to first explicit Axes.
758
747
748
+ # Explicit second Axes object has separate methods as well.
759
749
ax2 .set_xticks (months )
760
750
ax2 .set_xticklabels (months , rotation = 270 )
761
751
ax2 .set_title ('2010' , fontsize = 'small' )
762
- # Explicit second Axes object has separate methods as well.
763
752
753
+ # The pyplot module displays Figure.
764
754
plt .show ()
765
- # The pyplot module displays the Figure.
766
755
767
756
##############################################################################
768
757
#
0 commit comments