<jupyter_start><jupyter_text>IntroductionMatplotlib is a cross-platform python library for plotting 2D graphs(also called as plots). It can be used in a variety of user interfaces python scripts, IPython shells, Jupyter Notebooks, web applications. It can be used to develop interactive reporting applications, customized to develop complex dash board and imaging applications. It supports saving figures into various hard copy formats as well. It also has limited support for 3D figures. It also support many 3rd party extensions to extend its functionality.  Architecture of MatplotlibMatplotlib has a 3 layer architecture, Backend, Artist and Scripting, organised logically as a stack. Scripting is an API using which developers create the graphs. Artist is the one which does actual job of creating the graph internally. Backend is where the graph is displayed. Backend LayerThis is the bottom most layer where the graphs are displyed onto an output device. This can be any of the User Interfaces that Matplotlib supports. These are two types of Backends. User Interface Backends(for use in pygtk, wxpython, tkinter, qt4, or macosx etc. also referred to as “interactive backends”), and Hardcopy Backends to make image files (PNG, SVG, PDF, PS; also referred to as “non-interactive backends”). We will see how to configure to use any of these backends in later chapters Artist LayerThis is the middle layer of the stack. Matplotlib uses the artist object to draw various elements of the graph. So every element(see below elements of a Figure) we see in the graph is an artist. This layer provides object oriented API for plotting gaphs with maximum flexibility. This interface is meant for seasoned Python programmers, who can create complex dashboard applications. Scripting LayerThis is the topmost layer of the stack. This layer provides a simple interface for creating graphs. This is meant for use by end users who don't have much programming expertise. This is called as pyplot API.  Elements of a FigureThe high level matplotlib object that contains all the elements of the output graph is called $Figure$. Multiple graphs can be arranged in different ways to form a Figure. Each of the Figure elements is customizable.![image.png](attachment:image.png)  FigureThe whole picture shown above is called Figure. It contains all the elements of the picture. AxesAxes is a sub-section of the Figure, where a graph is plotted. Axes has a title, x-label and y-label. A Figure can have many such Axes, each representing one or more graphs. In the above Figure, there is only one Axes, two line graphs in blue and red colours AxisThese are number lines representing the scale of the graphs being plotted. 2D graphs have X-axis and Y-axis, 3D graphs have X-axis, Y-axis and Z-axis. Don't get confused between Axes and Axis. Axis is an element of Axes. LabelIt is the name given to various elements of the figure, e.g. X-axis label, Y-axis label, graph label(Blue Signal, Red Signal in the above Figure) etc. LegendWhen there are multiple graphs in the Axes(as in the above figure), each of them has its own label, and all these labels are represented as a legend. In the above figure Legend is placed at the top right corner of the figure. TitleIt is the name given to each of the Axes. Figure also can have its own title, when the Figure has multiple Axes with their own titles. Above Figure has only one Axes, so there is only title for the Axes as well as Figure Tick LabelsEach of the axis(X, Y or Z) would have a range of values that are divided into many equal bins. Bins are chosen at two levels. In the above Figure X-axis scale ranges from 0 to 4, divided into 4 Major bins(0, 1, 2, 3, and 4) and each of the major bins further divided into 4 minor bins (0, 0.25, 0.5, 0.75). Major bins are called Major Tick and Minor Bins are called Minor Tick, and the names given to them are called Major tick label and Minor tick label. SpinesBoundaries of the figure are called spines. There will be 4 spines for each figure(top, bottom, left and right). GridFor easier readability of co-ordinates of various points on the graph, the area of the graph is divided into a grid. Usually this grid is drawn along major ticks of X and Y axis. In the above figure, Grid is shown in dashed lines.  Interactive and non-interactive modesIn the interactive mode, graph gets updated in the backend after each statement. In the non-interactive mode, graph does not get displayed until explicitly asked to do so. Using the following commands, interactive mode can be set on or off, and also checked for current mode at any point in time.- matplotlib.pyplot.ion() to set the interactive mode ON- matplotlib.pyplot.ioff() to switch off interactive mode- matplotlib.is_interactive() to check whether interactive mode is ON(True) or OFF(False)<jupyter_code># Set the backend as the screen output
%matplotlib inline

# Import matplotlib and pyplot libraries. It is common practice in python to import libraries with crisp synonyms. 
# plt is the synonym for matplotlib.pyplot package
import matplotlib
import matplotlib.pyplot as plt

# Set the interactive mode to ON
plt.ion()

# Check the status of interactive mode
matplotlib.is_interactive()<jupyter_output><empty_output><jupyter_text>Plot a line graph connecting two points (0,1.5) and (1,3). The plot command expects two list/numpy array arguments for X and Y axis respectively. If you pass only one argument, it takes it as Y-axis and for X-axis it takes default range of 0 to 1. In the below example we are passing only one list of two points, which will be taken as Y-axis co-ordinates. For X-axis it takes the default values of 0 and 1 respectively.<jupyter_code>plt.plot([1.5, 3.0]);
# Plot a line graph
plt.plot([1.5, 3.0]);

# Add labels and title
plt.title("Interactive Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Plot a line graph
plt.plot([1.5, 3.0])

# Add labels and title
plt.title("Interactive Plot");
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# Add One more line graph
plt.plot([3.5, 2.5])<jupyter_output><empty_output><jupyter_text>__Note:__ Older versions of matplotlib or certain backends(e.g. macosx), graph may not be updated immediately. In such cases, you need to call plt.draw() explicitly at the end, so that graph gets displayed.  Non-Interactive Mode<jupyter_code># Start the kernel afresh, and import matplotlib and pyplot libraries
import matplotlib
import matplotlib.pyplot as plt

# Set the interactive mode to OFF
plt.ioff()

# Check the status of interactive mode
matplotlib.is_interactive()
# Plot a line graph
plt.plot([1.5, 3.0]);<jupyter_output><empty_output><jupyter_text>No output is displayed! To display the graph on the screen, you need to explicitly call the function plt.show()<jupyter_code># Display the graph on the screen 
plt.show()<jupyter_output><empty_output><jupyter_text>External Data for PlottingBy default matplotlib accepts input data as python list or Numpy array only. So all external data needs to be read and converted to either python list or Numpy array before feeding it to matplotlib for plotting the graphs. If the data is in txt file, you can use python functions to read the data and put it in Numpy array. If the data is in csv, xlsx formats you can use pandas library to read the data and put it into Numpy arrays.  Reading a text file and plotting a line graph<jupyter_code># Import numpy library with synonym np. numpy is a library to manage n-dimensional arrays supporting all 
# mathematical operations on these arrays
import numpy as np

# test.txt is a text file with 10 numbers separated by comma, representing x, y co-ordinates of 5 points(1,1),
# (2,4), (3,9), (4,16) and (5,25) in 2D space. loadtxt() is a numpy function to load text data into numpy array
txt = np.loadtxt('test.txt', delimiter = ',')
txt
# convert the flat array into 5 points in 2D space
txt = txt.reshape(5,2)
txt
# Separate x and y axis points. x is the first column in txt1 and y is second column. Python indexing starts with 0
x = txt[:,0]
y = txt[:,1]
print(x, y)
# import pyplot library
import matplotlib.pyplot as plt

# plot the graph
plt.plot(x, y)

# Display the graph on the screen
plt.show()<jupyter_output><empty_output><jupyter_text>Reading a csv file and plotting a graph<jupyter_code># .csv file has relational database structure of rows and columns. test.csv file has x,y co-ordiantes for 5 points 
# in 2D space. Each point is a row in the file, with 2 columns x and y. Same numpy loadtxt() function is used to load data
x, y = np.loadtxt ('test.csv', unpack = True, usecols = (0,1), delimiter = ',')
print(x)
print(y)
# import pyplot library
import matplotlib.pyplot as plt

# plot the graph
plt.plot(x, y)

# Display the graph on the screen
plt.show()<jupyter_output><empty_output><jupyter_text>Reading an xlsx file and plotting a graphxlsx file format is not supported by numpy. Pandas is a python data processing package that can be used to read xlsx files.<jupyter_code># import numpy package with np as synonym
import numpy as np
# import pandas package with pd as synonym
import pandas as pd
#Read xlsx file into pandas dataframe. This file has same 5 points in 2D space, each in a separate row with x, y columns
df = pd.read_excel('test.xlsx', 'sheet', header=None)
# Convert pandas dataframe to numpy array
data_array = np.array(df)
print(data_array)
# Extract x , y co-ordinates from the numpy array
x , y = data_array[:,0], data_array[:,1]
print(x,y)
# import pyplot library
import matplotlib.pyplot as plt

# plot the graph
plt.plot(x, y)

# Display the graph on the screen
plt.show()<jupyter_output><empty_output><jupyter_text>Environment Variables Setupmatplotlib uses matplotlibrc file to store default values for various parameters. It covers all the customisable parameters, hence, this file is very long. You can refer to matplotlib online documentation to get complete list of parameters. matplotlib.rcParams command is used to change these default values to any other supported values, one parameter at a time. matplotlib.rc command is used to set default values for multiple parameters within a specific group. Finally, matplotlib.rcdefaults() command is used to restore default paramaters. __Note:__ matplotlib.rcsetup() command is used internally by matplotlib to validate the parameters being changed are acceptable values<jupyter_code># Get the location of matplotlibrc file
import matplotlib
matplotlib.matplotlib_fname()
# .csv file has relational database structure of rows and columns. test.csv file has x,y co-ordiantes for 5 points 
# in 2D space. Each point is a row in the file, with 2 columns x and y. Same numpy loadtxt() function is used to load data
x, y = np.loadtxt ('test.csv', unpack = True, usecols = (0,1), delimiter = ',')

import matplotlib.pyplot as plt
# changing default values for multiple parameters within the group 'lines'
matplotlib.rc('lines', linewidth=4, linestyle='-', marker='*')

#changing default values for parameters individually
matplotlib.rcParams['lines.markersize'] = 20
matplotlib.rcParams['font.size'] = '15.0'

#Plot the graph
plt.plot(x,y)

# Display the graph
plt.show()
# To restore all default parameters
matplotlib.rcdefaults() 
plt.plot(x,y)
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.061778803479495825, 'fraction_numerical': 0.008787502219066217, 'mean_word_length': 4.684661957618567, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '268745', 'license': 'MIT', 'n_tokens_mistral': 3189, 'n_tokens_neox': 3065, 'n_words': 1685, 'path': 'Chapter01/Chapter 1 - Anatomy of Matplotlib.ipynb', 'repo_name': 'phucson/Matplotlib-3.0-Cookbook', 'size': '11266'}