Plot Types and Customizations
Explore how to customize various plot elements in Matplotlib such as line color, width, style, markers, and axis limits. Learn to create multiple plot types like scatter, histograms, and box plots to enhance your data visualization skills in Python.
We'll cover the following...
Line colors
Matplotlib provides several options to customize plots. These methods are introduced throughout the course. This lesson covers a subset of these methods.
The color and other graphical elements in a plot can be defined in several ways. The Matplotlib library uses MATLAB-like syntax, where 'r' means red, 'g' means green, and so on. The MATLAB API for selecting line styles is also supported in Matplotlib. For example, 'r.-' means a red line with dots.
The appropriate way to plot graphical elements is to plug in the color value in the following template: color=[parameter].
Colors can be specified by name or by RGB hex code. There is another very useful optional parameter, alpha, that can be used along with color to control opacity (this is useful when data points are stacked on each other).
Line marker, width, and style
Below is another example of plot customization using a range of related parameters to make our plot beautiful.
Next, extend plot customization to improve figure clarity and presentation. This section covers how to:
- Change the line width with the
linewidthorlwkeyword argument. - Change the line style with
linestyleorlskeyword arguments. - Set the marker with
markerandmarkersizekeyword arguments.
The code and figure below are a good reference for creating attractive plots.
Matplotlib also allows control over the axes. We can set the x and y limits using set_xlim and set_ylim methods. We can also use axis('tight') to automatically get “tightly fitted” axes ranges.
Let’s see examples of this:
Scatter plot
We create a variety of plots while practicing data science. Some of the most commonly used plots are histograms, scatter plots, bar plots, pie charts, and so on. This library supports creating a wide range of plots with concise code.
Let’s start with the scatter plot, which we can create with plt.scatter(x,y):
The following examples demonstrate additional plot types. These examples build familiarity with different plot types.
Histograms
We can create histograms using Matplotlib. Let’s explore this by taking some random data and using the plt.hist() method to create a histogram.
Box plot
We can also create boxplots using Matplotlib.
Let’s learn this with an example: