Plotting fundamentals in Matplotlib

Plotting with Matplotlib

Matplotlib is a Python library for creating 2D plots and visualizations. It can generate high-quality figures that can be used in various formats and environments. To use Matplotlib in your notebook environment, you need to set it up so that the plots are displayed inline as images. This is the first step in working with Matplotlib and creating plots in your notebook.

The code above will import the required libraries and there will be no output to it.

Generate Data

Now we generate some data to use while experimenting with plotting:

Matplotlib has two main objects that are used to create plots:

  • the Figure: A Figure object holds one or more Axes objects and is used to save the plots to files in different formats (e.g. PNG, SVG).

  • the Axes: An Axes object represents an individual plot with an x-axis, a y-axis, labels, and various methods for creating plots.

Regenerate response

To create a plot using Matplotlib, you can specify the size of the Figure object in inches and create an Axes object on it. Then, you can use the plot method of the Axes object to plot the data, providing the data for the x-axis (independant values) and y-axis (dependent values) as arguments. In this case, the times and temps data are plotted on the x-axis and y-axis, respectively.

Line Plot

Axes

From there, we can do things like ask the axis to add labels for x and y:

Title

We can also add a title to the plot:

Of course, we can do so much more…

Plotting Multiple Lines with different Line styles

When creating plots using Matplotlib, you have the flexibility to customize the appearance of the plot by modifying style attributes such as linestyle and color . The color attribute can take a variety of values, including named colors like red or blue , as well as HTML color codes. In this case, the tab:red value is being used to specify a shade of red from the Tableau color set in Matplotlib. This allows you to customize the appearance of your plots to meet your specific needs and preferences.

Scatter Plot

If you want to plot your data as a scatter plot rather than a line plot, you can modify the linestyle attribute to none and specify a marker type, size, and color. Alternatively, you can use the scatter method, which is slower but allows you more control over the appearance of the plot, such as the ability to color the points individually based on a third variable. This can be useful if you want to visualize the relationships between different variables in your data.

1 Like