Tuesday, September 24, 2024

Creating your first plot (plt.plot())

For first plot using matplotlib library we will create a line graph. The line graph is created using the plot function of the matplotlib library. The plt.plot() function in general form is written as:
matplotlib.pyplot.plot(*args, scalex = True, scaley = True, data = None, **kwargs)
            
The parameters inside the plot function are:
  • *args - this is a flexible parameter that can take different types of inputs. The examples of these inputs are:
    • a single sequence for \(y\) values (the x values will default to range(len(y))),
    • two sequences \(x\) and \(y\) data points,
    • multiple x and y pairs (useful for plotting multiple lines).
      plot([1,2,3,4])
      plot([1,2,3,4], [10,20,35,50])
      plot([1,2], [3,4], [5,6], [7,8])
  • scalex = True - this parameter automatically scales the x-axis to the data if set to True. If False, it will not rescale even if the data exceeds the current axis limits.
  • scaley = True - this parameter works the same as the scalex but for the y-axis. If True, if automatically scales the y-axis to the data.
  • data = None - this allows you to pass a data structure (dictionary or pandas DataFrame), so that instead of passing actual arrays or sequences for \(x\) and \(y\), you can refer to the names or keys of the data. This is useful for plotting irectlyfrom complex data structures i.e.
    data = {'x': [1,2,3,4], 'y':[10,20,25,30]}
    plot('x', 'y', data=data)
    
  • **kwargs - These are additional keyword arguments that can be used to customize the plot such as: color, linestyle, marker, label...
In this example we will plot the line plot that connects points with the following x and y coordinates. \begin{eqnarray} x &=& [1,2,3,4] \\ \nonumber y &=& [23,445,567,3] \end{eqnarray} The first step is to define the required libraries. If you have correctly installed the matplotlib library then type in the following code in your Python script.
import matplotlib.pyplot as plt
The second step is to define the data points (coordinates) that will be plotted using the line plot.
x = [1,2,3,4,5,6]
y = [2,4,7,8,10,12]
When the library and the data points are defined then we can define the required matplotlib functions to show the line graph. In this case we will need to define the figure size using plt.figure(figsize=(12,8)) function,plt.plot for creating the line plot, grid to display the grid to improve the readability, xlabel and ylabel to show the labels of the x and y axes, and finally the show function to display the line plot.
plt.figure(figsize=(12,8))
plt.plot(x,y)
plt.grid(True)
plt.xlabel("x")
plt.ylabel("y")
plt.show()
The entire code created in this example is shwon below.
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6]
y = [2,4,7,8,10,12]
plt.figure(figsize=(12,8))
plt.plot(x,y)
plt.grid(True)
plt.xlabel("x")
plt.ylabel("y")
plt.show()
When the previous code is executed the line plot is generated as shwon in Figure.
2024-09-25T02:05:20.622345 image/svg+xml Matplotlib v3.8.0, https://matplotlib.org/
Figure 1 - Line plot created using pyplot.plot() funciton.
The previous block of code responsible for creating line plot in Figure 1 consist of the following matplotlib.pyplot functions:
  • plt.figure(figsize=(12,8))
    • plt.figure()- the plt is the common alias for the matplotlib pyplot module (it was previously explained when we imported the matplotlib library).
    • figure() - is the function that creates new figure in which you can plot your data If you forget to define it explicitly, the matplotlib will create one automatically when you start plotting. However the default figsize would be 6.4 by 4.8 which is width and height in inches.
    • figsize=(12,8) - - the figsize is the parrameter that specifies the sie fo the figure in inches. The parameter is a tuple that contains two values:
      • width - the first value in the tuple (12) represents the width of the figure.
      • height - the second vlaue (8) represents the height of the figure
    • numbers 12 and 8 - the size is given in inches beacuse Matplotlib uses inches as the unit of measure for figure dimensions. A figure with a size of (12,8) will be 12 inches wide and 8 inches tall.
    • dots per inch - the actual number of pixels in the figure is determined by the DPI setting and its 100 DPI by default. So , a figure with a 12x8 would have 1200 x 800 pixle size (12 inches * 100 DPI by 8 inches * 100 DPI).
  • plt.plot(x,y) - the plot() function is the pyplot function used for creating the 2D plots, usually a line plot, based on the provided data. The x and y are data points that you want to plot. The x represents the data for the x-axis.It is usally a list, array, or other iterable containing numerical values.y represents the data for the y-axis. As the x the y can also be a list, array, or another iterable containing numerical values. However, the length of the y must be the same as x.The plot function will connect each pair of points (x[i],y[i]) whit a line, creating a continuous line plot. The command matches each element in x with the corresponding element in y. For example x = [1,2,3,4,5,6] and y = [2,4,7,8,10,12] the function plots the points (1,2), (2,4), (3,7), (4,8), (5,10), and (6,12) and connects them with a line.
  • plt.grid(True) - This function is used to toggle the visibility of the grid lines on the plot. The True argument turns on the grid lines. This means the grid lines will be displayed on the plot. In case the False value is inside the brackets it will turn off the grid lines. The puprose of grid lines is to enhance the readability i.e. grid lines help improve the readability of the plot by making it easire to aling and iterpret data points, especially when the plot contains multple lines or data points.
  • plt.xlabel('x'), plt.ylabel('y')- xlabel and ylabel are functions used to set a label for x-axis and y axis of the current plot. The x or y argument are labels you want to display along the x and y-axis respectively. For example try changing the xlabel argument to "time (s)" and the ylabel argument to "Temperature [K]" and see what happens.
  • plt.show() - is the matplotlib command that displays the current plot or figure. It opens a window with the plot, allowing you to visualize the data. This function is essential for creating plots in scripts or interactive enviroments, as it renders the plot on the screen. After the commnad is called, the figure is displayed and the script execution continues or it ends if this sis the last command in the script.

Monday, September 23, 2024

Introduction to Matplotlib

The Matplotlib library is one of the most popular and widely-used data visualization libraries in Python programming language, offering versatile tools for developing a wide range of static, animated, and interactive plots. In this tutorial the individual can learn Matplotlib basics and quickly become an expert. But before that this first part of the tutorial will introduce Matplotlib, outline the importance of the Python ecosystem, and explain the differences between its interfaces, such as pyplot and object-oriented API.

What is Matplotlib?

The Matplotlib as previously stated is a library used to create static, animated and interactive visualizations in Python programming language. It provides an interface to generate high-quality plot and graphs ranging from simple line plots to complex 3D visualizations. This tool is so good and easy to use that it often the first tool data scientists, analysts, and engineers turn to when they need to visually explore their data. By providing users the control over every aspect of the plot (axes, markers, labels, color...) Matplotlib is a versatile tool that can generate professional-grade visualizations.

How to install and setup Matplotlib?

The installation of Matplotlib is pretty straightforward. If you have installed Python and have installed pip installer then open the Command Prompt Window or Terminal and simply type in the following command:
pip install Matplotlib
If you have installed the Anaconda distribution of Python or have the conda environment then open the command prompt or terminal and type in the following command:
conda install Matplotlib
When the Matplotlib is installed you can immediately start creating visualizations. Matplotlib is compatible with various Python environments, including Jupiter Notebooks, Python scripts, and integrated developed environment like VS code.

Understanding the Matplotlib Ecosystem

The Matplotlib ecosystem is a broad and flexible environment for creating visualizations in Python, and it serves as the foundation for many plotting libraries. At its core, Matplotlib provides a vast set of tools for generating static, interactive, and animated visualizations. It is often used alongside other libraries, making it highly versatile in a variety of applications, from data science to engineering.

At the heart of Matplotlib is the Pyplot module, which offers a state-based interface similar to MATLAB, allowing users to quickly generate plots. However, Matplotlib's true power lies in its object-oriented API, which provides fine-grained control over figures, axes, and plot elements. This enables users to create highly customized visualizations, manage multiple plots, and design complex layouts with ease.

Another key component is Axes, the part of a figure where the data is plotted. Each figure can contain multiple axes, allowing for the creation of grids of plots or advanced layouts. The Figure object represents the entire drawing canvas, and understanding the relationship between figures, axes, and other plot elements is essential for creating detailed plots.

Matplotlib integrates with other Python libraries such as NumPy, Pandas, and SciPy, making it the backbone of the Python data visualization ecosystem. This integration allows for seamless plotting of data structures like arrays and dataframes, making it ideal for tasks ranging from exploratory data analysis to publication-ready visualizations.

In addition to static plots, Matplotlib supports interactive plotting, where users can zoom, pan, and adjust plots in real time, especially useful in environments like Jupyter Notebooks. For more sophisticated needs, Seaborn builds on Matplotlib by providing high-level interfaces for statistical graphics. Likewise, Pandas incorporates Matplotlib under the hood, making it easy to generate quick plots from dataframes.

Overall, the Matplotlib ecosystem is a comprehensive and flexible system for plotting in Python, capable of supporting both beginners and advanced users with diverse plotting needs, from basic charts to highly customized visual analytics.

Pyplot vs Object-Oriented API

Matplotlib provides two primary interfaces for generating plots. The pyplot interface which is very easy to use and the object-oriented API.

Plotly interface

The pyplot module mimics MATLAB's plotting functions. It is quick and easy to generate plot in an interactive manner. The pyplot interface handles many details behind the scenes, making it ideal for beginners or for quick visualizations. The example usage of plotly interface is shown in the following block of code.
import nmatplotlib.pyplot as plt 
plt.plot([1,2,3,4])
plt.show()

Object-oriented API

The API method is more flexible and enables finer control over the individual components of the plot, such as figure, axes, labels, and titles. The object-oriented API is recommended for complex visualizations or when creating reusable and extensible code. The example code of using object-oriented API is shown below:
import matplotlib.pyplot as plt 
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])
ax.set_title("Object-Oriented Example")
plt.show()
As seen from previous code block to use the object-oriented API approach the matplotlib.pyplot module must be imported just like in the classic plotly approach. It should be noted that users preferences and the plot complexity are the most important factors when choosing the appropriate approach i.e. plotly interface and the object-oriented API.

When to use Pyplot and when Object-Oriented API?

As previously described the Matplotlib as two primary ways to create plot:
  1. Pyplot (plt) interface: a simpler, state-based interface, good for quick, simple plots.
  2. Object-Oriented API: provides more flexilbility and control, especially when dealing with more complex plots.

When to use Pyplot (plt)?

  • Quick plots: If you're just creating a simple plot and need something fast and straightforward, plt is perfect.
  • Interactive plotting: For quick, interactive visualization in environments like Jupyter Notebooks.
  • Small scripts: For small scripts where plot customization is minimal and there are no complex subplots.

When to Use the Object-Oritented API?

  • Multiple plots - When you need to manage multiple figures, axes, or subplots.
  • Complex Layouts - When creating complex, multi-panel figures, the object-oriented API gives you more control over each plot element.
  • Fine Control - When you need to control specific plot elements like axes, labels, or legends, the object-oriented approach makes this easier.
  • Reusability - It's useful when writing modular code where plot customization needs to be reused or passed into functions.
To summarize, use the plt for quick and simple plots. Use the object-oriented API when you need more control and are working with complex layouts with multi-panel figures.

Other visualization libraries in Python (Seaborn, Plotly, etc.)

While Matplotlib is a robust visualization tool, Python has several other popular libraries that are worth mentioning:
  • Seaborn: Built on top of Matplotlib, Seaborn simplifies statistical plotting. It provides more advanced default styles and simplifies the process of creating complex visualizations such as heatmaps and pair plots.
    import seaborn as sns
    sns.set(style="darkgrid")
    sns.lineplot(x=[1, 2, 3], y=[1, 4, 9])
    
  • Plotly: A library for creating interactive visualizations. Plotly is ideal for web-based visualizations that allow zooming, panning, and other interactions. It also supports 3D plotting and is commonly used for dashboards.
    import plotly.express as px
    fig = px.line(x=[1, 2, 3], y=[1, 4, 9], title="Plotly Line Plot")
    fig.show()
    
  • Bokeh: Known for its interactivity and ability to handle large datasets. It is well-suited for building data-driven web applications.
Each of these libraries has its own strengths, but Matplotlib remains a foundational tool upon which many other libraries are built.

Setting up your environment

Setting up a proper environment is essential for working effectively with Matplotlib and other visualization libraries. You need to install the required packages and configure your IDE for optimal development experience.

IDE setup (Jupiter Notebook, VS Code, etc..)

Choosing the right Integrated Development Environment (IDE) is crucial for productivity when working with visualizations. Here are some popular options:
  • Jupyter Notebooks: Jupyter is widely used for data analysis because it allows users to write and execute code in cells. Visualizations are displayed directly in the notebook, making it easy to iteratively develop plots. To ensure Matplotlib renders inline in Jupyter, use:
    %matplotlib inline
    
  • VS Code: VS Code is a lightweight editor with rich extensions for Python development. The "Python" extension integrates well with Jupyter notebooks and provides powerful debugging tools.
To view plots in VS Code, use the interactive window by running cells in .py files or install Jupyter support.

Basic Imports and Conventions

Before creating plots, it's a common convention to import Matplotlib's pyplot module and set up default styles:
import matplotlib.pyplot as plt

# Set the default style for consistency
plt.style.use('ggplot')
This ensures that your plots have a consistent and professional appearance across your codebase. You can also adjust default parameters like figure size, fonts, and colors using matplotlib.rcParams to create a personalized plotting environment.