In today’s data visualization tutorial we’ll learn how to quickly plot line charts using Python as well as the Matplotlib and Pandas libraries.
Importing Python charting libraries
Let’s get started by importing the required libraries into our Python development environment. I use Jupyter Lab, but you can use other notebooks or Python IDEs.
import matplotlib.pyplot as plt import pandas as pd import numpy as np
Creating a Dataset for our example
Let’s now create some test data arrays. We’ll also go ahead and create a Pandas DataFrame, so we can also show some Pandas plotting capabilities.
x = np.linspace (1,50,25) y = np.log(x) # Create a Pandas DataFrame chart_df = pd.DataFrame(dict(x=x,y=y))
Create a python plot line with Matplotlib
Rendering the chart is quite simple, we’ll also include a title and labels for the axes:
plt.plot(x,y) # Adding a title plt.title('Business trip costs') # Adding labels to the axes plt.xlabel ('Duration') plt.ylabel('Overall Cost');
And here’s our simple graph:
Customizing the line plot style, size and colors
There is a significant amount of customization options available for the Line2D object in Matplotlib. In the following example we’ll modify the line style: width, marker type, color and width. We’ll pass those to the kwargs (Keyword arguments) parameter. The values for the different line properties are somewhat self explanatory:
kwargs = dict (linestyle='--', color='g', marker ='o', linewidth=1.3)
And then call the plt.plot() method:
plt.plot(x,y, **kwargs) plt.title('Business trip costs') plt.xlabel ('Duration') plt.ylabel('Overall Cost');
Here’s our customized chart:
Note: we can easily change the line markers size using the markersize parameter. In that case we’ll pass the following kwargs parameters:
kwargs = dict (linestyle='--', color='g', marker ='o', linewidth=1.3, markersize=12.5)
Python line plots for DataFrames with Pandas
We can also use the Pandas library to render static graphs as it wraps some of the Matplotlib capability which you can invoke directly on your Dataframe.
We previously defined a DataFrame that we’ll now use four our graph creation:
# define the style of our line chart kwargs = dict (linestyle='dotted', color='b', linewidth=1.3) #Render a plot directly from our Pandas DataFrame chart_df.plot(x='x', y='y',kind='line', **kwargs);
Here’s the result (note the usage of the linestyle=’dotted’ to deliver a line chart of dots.