Plot Types and Customizations
Let’s learn about setting the color of lines, the width between lines, and the marker styles of lines with matplotlib.
We'll cover the following...
Line colors
There are lots of options available in matplotlib to customize a plot. These methods will keep coming throughout this course. We’lls explore a few of these in this lesson.
The color and other graphical elements in a plot can be defined in a number of 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 used both by their names and their RGB hex codes. 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.
Let’s move on and explore a little more about how to make our plot figures more attractive. We’ll go over 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. It’s very easy to create all of these plots using this state-of-the-art Python library.
Let’s start with the scatter plot, which we can create with plt.scatter(x,y):
Now, let’s look at some more examples to familiarize ourselves with the other types of plots. With time and practice, you’ll be an expert in all of these plots!
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.
Boxplot
We can also create boxplots using matplotlib.
Let’s learn this with an example: