#120 Line chart with matplotlib

A line chart or line graph is a type of chart which displays information as a series of data points called ‘markers’ connected by straight line segments. It is similar to a scatter plot except that the measurement points are ordered (typically by their x-axis value) and joined with straight line segments.

Basic lineplot

This post describes how the plot function of matplotlib works. If you give only a serie of values, matplotlib will consider that these values are ordered and will use values from 1 to n to create the X axis (figure 1):

# libraries
import matplotlib.pyplot as plt
import numpy as np

# create data
values=np.cumsum(np.random.randn(1000,1))

# use the plot function
plt.plot(values)
Seaborn customization

For a more trendy look, just load the seaborn library. You will automatically get the look of figure 2.

 
# libraries 
import matplotlib.pyplot as plt 
import numpy as np 
import seaborn as sns

# create data 
values=np.cumsum(np.random.randn(1000,1)) 

# use the plot function 
plt.plot(values) 

Use lineplot with ordered data !

Of course you can make a line chart from 2 series of values (X and Y axis). However, make sure that your X axis values are ordered! If not you will get this kind of figure (figure 3).

# libraries and data
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
df=pd.DataFrame({'xvalues': range(1,101), 'yvalues': np.random.randn(100) })

# plot
plt.plot( 'xvalues', 'yvalues', data=df)
plt.show()
Use lineplot with ordered data !

If your X data are ordered, then you will get the same figure than figure 1:

# libraries
import matplotlib.pyplot as plt
import seaborn as sns

# import the iris dataset
df = sns.load_dataset('iris')

# plot
plt.plot( 'sepal_width', 'sepal_length', data=df)
plt.show()

Leave a Reply

Your email address will not be published.