# Matplotlib plot a line (Detailed Guide)

In this Python tutorial, we will discuss, How to plot a line chart using matplotlib in Python with different features, and we shall also cover the following topics:

• Matplotlib plot a line chart
• Matplotlib plot line style
• Matplotlib plot line thickness
• Matplotlib plot line color
• Matplotlib plot a line between two points
• Matplotlib plot a horizontal line
• Matplotlib plot a vertical line
• Matplotlib plot horizontal line with label
• Matplotlib plot horizontal line on bar graph
• Matplotlib plot vertical line at date
• Matplotlib plot vertical line with text
• Matplotlib plot vertical line on histogram
• Matplotlib plot a linear function
• Matplotlib plot point on line graph
• Matplotlib scatter plot straight line
• Matplotlib plot line graph from dataframe
• Matplotlib plot a line in 3D

## Matplotlib plot a line chart

Matplotlib is the widely used data visualization library in Python. It provides a variety of plots and data visualization tools to create 2D plots from the data in lists or arrays in python. Matplotlib is a cross-platform library built on NumPy arrays.

You can create line charts in python using the pyplot submodule in the matplotlib library. Pyplot provides a collection of related functions for a variety of plots. Line charts visualize the relationship between two quantities on X-axis and Y-axis on the X-Y cartesian plane.

You can create a line chart by following the below steps:

• Import the required libraries (pyplot from matplotlib for visualization, numpy for data creation and manipulation).
• Defining the data values that has to be visualized (Define x and y).
• Plot the data by adding the features you want in the plot (plot color, thickness, labels, annotation, etc…).
• Display the plot (graph/chart).

Let’s plot a simple line in python. So, open up your notebook, not the physical one, open jupyter notebook, and follow the code below:

``````# Importing packages
import matplotlib.pyplot as plt

# Define x and y values
x = [7, 14, 21, 28, 35, 42, 49]
y = [8, 13, 21, 30, 31, 44, 50]

# Plot a simple line chart without any feature
plt.plot(x, y)
plt.show()``````

## Matplotlib plot line style

You can change the line style in a line chart in python using matplotlib. You need to specify the parameter linestyle in the plot() function of matplotlib.

There are several line styles available in python. You can choose any of them. You can either specify the name of the line style or its symbol enclosed in quotes. You can search for the available line styles, I have given examples for some commonly used line styles.

Examples :

``````# Importing packages
import matplotlib.pyplot as plt

# Define x and y values
x = [7, 14, 21, 28, 35, 42, 49]
y = [8, 13, 21, 30, 31, 44, 50]

# Plot a simple line chart with 'solid' linestyle
plt.plot(x, y, linestyle='-')
plt.show()

# Plot a simple line chart with 'dashed' linestyle
plt.plot(x, y, linestyle='dashed')
# Or you can use: plt.plot(x, y, linestyle='--')
plt.show()

# Plot a simple line chart with 'dotted' linestyle
plt.plot(x, y, ':')
plt.show()

# Plot a simple line chart with 'dash_dot' linestyle
plt.plot(x, y, '-.')
plt.show()``````

## Matplotlib plot line thickness

You can change the line thickness in a line chart in python using matplotlib. You need to specify the parameter linewidth in the plot() function of matplotlib.

Examples :

``````# Importing packages
import matplotlib.pyplot as plt

# Define x and y values
x = [7, 14, 21, 28, 35, 42, 49]
y = [8, 13, 21, 30, 31, 44, 50]

# Plot a simple line chart with linewidth 7
plt.plot(x, y, linewidth=7)
plt.show()

# Plot a simple line chart with 'dash_dot' linestyle and linewidth 3
plt.plot(x, y, '-.',linewidth=3)
plt.show()``````

## Matplotlib plot line color

You can change the line color in a line chart in python using matplotlib. You need to specify the parameter color in the plot() function of matplotlib.

There are several colors available in python. You can choose any of them. You can either specify the name of the color or the symbol of it or you can give the hex code of the color enclosed in quotes. You can search for the available colors.

Examples :

``````# Importing packages
import matplotlib.pyplot as plt

# Define x and y values
x = [7, 14, 21, 28, 35, 42, 49]
y = [8, 13, 21, 30, 31, 44, 50]

# Plot a simple line chart with green as line color
plt.plot(x, y, ':', linewidth=7, color='green')
plt.show()

# Plot a simple line chart with red as line color
plt.plot(x, y, 'r', linestyle='--', linewidth=5)
plt.show()

# Plot a simple line chart with yellow as line color
plt.plot(x, y, 'y-.', linewidth=3)
plt.show()

# Plot a simple line chart with neon purple (Hexcode='#B026FF') as line color
plt.plot(x, y, color='#B026FF', linewidth=1)
plt.show()``````

## Matplotlib plot a line between two points

You can plot a line between the given two points in python using matplotlib by specifying those two points in the x-axis and y-axis value lists.

Example :

``````# Importing packages
import matplotlib.pyplot as plt

# Define x and y values
x = [7, 42]
y = [8, 44]

# Plot a simple line chart between two points (7, 8) and (42, 44)
plt.plot(x, y, linewidth=7, color='green')
plt.show()

# OR

# Plot a simple line chart between two points (2, 5) and (6, 10)
plt.plot([2, 6], [5, 10], 'r', linewidth=5)
plt.show()``````

## Matplotlib plot a horizontal line

You can plot a horizontal line in matplotlib python by either using the plot() function and giving a vector of the same values as the y-axis value-list or by using the axhline() function of matplotlib.pyplot that accepts only the constant y value.

The range of the line drawn by the axhline() function is from 0 to 1 only, while in the plot() function you can give a vector of two values specifying the range as x value-list.

Example :

``````# Importing packages
import matplotlib.pyplot as plt

# Define x and y values
x = [7, 49]
y = [8, 8]

# Plot a horizontal line
plt.plot(x, y, 'y', linewidth=3)
plt.show()

# OR

# Plot a horizontal line using axhline() in pyplot
plt.axhline(y=8, xmin=0.1, xmax=0.8, color='r', linestyle='-.', linewidth=3)
plt.show()``````

## Matplotlib plot a vertical line

You can plot a vertical line in matplotlib python by either using the plot() function and giving a vector of the same values as the y-axis value-list or by using the axvline() function of matplotlib.pyplot that accepts only the constant x value.

You can also use the vlines() function of the matplotlib. pyplot, which we will discuss later. The range of the line drawn by the axvline() function is from 0 to 1 only, while in the plot() function you can give a vector of two values specifying the range as the y-axis value-list.

Example :

``````# Importing packages
import matplotlib.pyplot as plt

# Define x and y values
x = [8, 8]
y = [7, 49]

# Plot a vertical line
plt.plot(x, y, 'b', linewidth=3)
plt.show()

# OR

# Plot a vertical line using axvline() in pyplot
plt.axvline(x=8, ymin=0.1, ymax=0.8, color='g', linestyle=':', linewidth=3)
plt.show()``````

## Matplotlib plot horizontal line with label

You can specify the label to any plot in matplotlib python by adding a label parameter in the plot() function where you can specify any string enclosed in quotes.

Example :

``````# Importing packages
import matplotlib.pyplot as plt

# Define x and y values
x = [7, 49]
y1 = [3, 3]
y2 = [8, 8]

# Plot a horizontal line
plt.plot(x, y1, '-r', linewidth=3, label='red line')
plt.plot(x, y2, '-b', linewidth=3, label='blue line')
plt.legend()
plt.show()

# OR

# Plot a horizontal line using axhline() in pyplot
plt.axhline(y=3, xmin=0.1, xmax=0.8, color='r', linestyle='-.', linewidth=3, label='red line')
plt.axhline(y=8, xmin=0.1, xmax=0.8, color='b', linestyle='-.', linewidth=3, label='blue line')
plt.legend()
plt.show()``````

## Matplotlib plot horizontal line on bar graph

You can plot any type of plot over another plot in matplotlib python by specifying multiple plot statements before saving/displaying the figure. In the same way, you can plot a horizontal line on the bar graph. Let’s do an interesting example.

Example :

``````# Importing packages
import matplotlib.pyplot as plt
import numpy as np

# Define x values and heights for the bar chart
heights = np.array([7.0, 28.0, 14.0, 35.0, 42.0, 21.0, 49.0])
x = range(len(heights))

# y value from where the horizontal line has to be drawn
y_val = 24.0

# we are splitting the heights to create a stacked bar graph by the y_val
upper_bars = np.maximum(heights - y_val, 0)
lower_bars = np.minimum(heights, y_val)

# Plotting the stacked bar graph
plt.bar(x, lower_bars, width=0.5, color='y')
plt.bar(x, upper_bars, width=0.5, color='r', bottom=lower_bars)

# Plotting the horizontal line to divide through the y_val
plt.axhline(y=y_val, color='b', linestyle=':', label='red line')

plt.show()``````

## Matplotlib plot vertical line at date

You can add dates as ticklabels and can plot vertical lines at a date in matplotlib python. You need to import the datetimes function from datetime module in python for creating the date-formatted values.

You need mdates sub-module from the matplotlib.dates to format the dates for the plot. You can follow the simple example given below to understand the way to do it.

Example :

``````# Importing packages
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
from datetime import datetime

fig, ax = plt.subplots()
dates = np.array([datetime(2020,1,1), datetime(2020,6,30), datetime(2021,1,1)])
dates = mdates.date2num(dates)

ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y'))
ax.xaxis.set_major_locator(mdates.YearLocator())

plt.vlines(x=dates, ymin=0, ymax=10, color = 'g')

plt.show()``````

## Matplotlib plot vertical line with text

You can also add text to the plot at any given position. You need to use the text() function from the matplotlib.pyplot where you have to specify the text to be added, and the x and y positions on the X-Y Plane of the plot.

In the below example I am using a loop to add texts iteratively to all the vertical lines drawn in the example of the previous topic.

Example :

``````# Importing packages
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
from datetime import datetime

fig, ax = plt.subplots()
dates = np.array([datetime(2020,1,1), datetime(2020,6,30), datetime(2021,1,1)])
dates = mdates.date2num(dates)

ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y'))
ax.xaxis.set_major_locator(mdates.YearLocator())

plt.vlines(x=dates, ymin=0, ymax=10, color = 'r', linewidth=2)

for i, x in enumerate(dates):
text((x+5), 5, "Interval %d" % (i+1), rotation=90, verticalalignment='center')

plt.show()``````

## Matplotlib plot vertical line on histogram

You can plot a vertical line on a histogram in matplotlib python by specifying multiple plot statements before saving/displaying the figure. In the same way, we have discussed in previous topics. Let’s do an interesting example to understand the need for such types of graphs.

Example :

``````# Importing packages
import matplotlib.pyplot as plt
import numpy as np

# Generating a random seed
np.random.seed(1)

# A sample is drawn from a Gamma distribution with shape 3, scale 0.7 and size 500
x = np.random.gamma(3, 0.7, 500)

# Plot a histogram for the sample data created
plt.hist(x, bins=30, color='y', edgecolor='r', alpha=0.70)

# Plot a vertical line at the mean of the sample data
plt.axvline(x.mean(), color='b', linestyle=':', linewidth=2)

plt.show()``````

## Matplotlib plot a linear function

A linear function represents a straight line on the graph. You can use the slope-intercept form of the line that is y = m * x + c; Here, x and y are the X-axis and Y-axis variables respectively, m is the slope of the line, and c is the x-intercept of the line.

You can visualize this function by populating the data for one of the variable lists (x or y), calculating the other variable by using the linear function formula, and plot the data points generated.

Example :

``````# Importing packages
import matplotlib.pyplot as plt
import numpy as np

# Creating a sample data for x-values
x = np.arange(2, 300, 4)

# Provide parameters of the linear function
m, c = 0.4, 1.6

# Calculating the y-values for all the x'-values
y = (m * x) + c

# Plotting the line created by the linear function
plt.plot(x, y, 'c', linewidth=2, label='y=m*x+c')
plt.title('Linear Function (y=m*x+c) plot')
plt.xlabel('x-values')
plt.ylabel('y-values')
plt.legend()
plt.show()``````

## Matplotlib plot point on line graph

You can mark the points on the line graph in matplotlib python by adding the marker parameter in the plot() function. You can specify any of the types of markers available in python.

Example :

``````# Importing packages
import matplotlib.pyplot as plt

# Define x and y values
x = [7, 14, 21, 28, 35, 42, 49]
y = [8, 13, 21, 30, 31, 44, 50]

# Plot points on the line chart
plt.plot(x, y, 'o--y', linewidth=2)
# Or plt.plot(x, y, marker='o', linestyle='--', color='y', linewidth=2)
plt.show()``````

## Matplotlib scatter plot straight line

You can plot a straight line on a scatter plot, or you can plot a straight line that fits the given scattered data points well (linear regression line) in matplotlib python by using a function polyfit() in numpy module of python, which is a general least-squares polynomial fit function that accepts the data points (x-axis and y-axis data), and a polynomial function of any degree, here in our case degree is 1 (linear).

It returns an array of the parameters (slope and intercept) of the best fit line for the given data. Then you can plot the line with the resulted parameters.

Example :

``````# Importing packages
import matplotlib.pyplot as plt
import numpy as np

# Define x and y values
x = np.array([7, 11, 24, 28, 35, 34, 41])
y = np.array([8, 20, 13, 30, 31, 48, 50])

# Drawn a simple scatter plot for the data given
plt.scatter(x, y, marker='*', color='k')

# Generating the parameters of the best fit line
m, c = np.polyfit(x, y, 1)

# Plotting the straight line by using the generated parameters
plt.plot(x, m*x+c)

plt.show()``````

## Matplotlib plot line graph from dataframe

You can plot the graph from a dataframe either by using the matplotlib.pyplot.plot() function or by using the dataframe.plot() function in python. We have already discussed the first function.

The later function is similar to the first one, just one difference is there, you need to specify the columns as the x-axis values and y-axis values in the function.

``````import pandas as pd

# Let's create a Dataframe using lists
countries = ['Monaco', 'Singapore', 'Gibraltar', 'Bahrain', 'Malta',
'Guernsey', 'Vatican City', 'Jersey', 'Palestine',
'Mayotte', 'Lebnon',
'Barbados', 'Saint Martin', 'Taiwan', 'Mauritius', 'San Marino']
pop_density = ['19341', '8041', '5620', '2046', '1390',
'1719', '1181', '1261', '1094', '2706',
'924.5', '929', '808', '686', '656',
'667', '654', '652', '644', '554']

# Now, create a pandas dataframe using above lists
df_pop_density = pd.DataFrame(
{'Country' : countries, 'Population Density(/kmsq)' : pop_density})

df_pop_density``````
``````import matplotlib.pyplot as plt

# Plotting the data from the dataframe created using matplotlib
plt.figure(figsize=(9, 5))
plt.title('Countries with higher population density (per km sq)')
plt.plot(df_pop_density['Country'], df_pop_density['Population Density(/kmsq)'], '-b', linewidth=2)
# OR : df_pop_density(x='Country', y='Population Density(/kmsq)', '-b', linewidth=2)
plt.xticks(rotation=60)
plt.xlabel('Countries')
plt.ylabel('Population Density')
plt.show()``````

## Matplotlib plot a line in 3D

You can plot a line in 3D in matplotlib python by importing mplot3d from the module mpl_toolkits, an external toolkit for matplotlib in python used for plotting of the multi-vectors of geometric algebra. Let’s do a simple example to understand it.

Example :

``````# Importing packages
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d

# Setting 3 axes for the graph
plt.axes(projection='3d')

# Define the z, y, x data
z = np.linspace(0, 1, 100)
x = 3.7 * z
y = 0.6 * x + 3

# Plotting the line
plt.plot(x, y, z, 'r', linewidth=2)
plt.title('Plot a line in 3D')
plt.show()``````

In this Python tutorial, we have discussed, How to plot a line chart using matplotlib in Python with different features, and we have also covered the following topics:

• Matplotlib plot line style
• Matplotlib plot line thickness
• Matplotlib plot line color
• Matplotlib plot a line between two points
• Matplotlib plot a horizontal line
• Matplotlib plot a vertical line
• Matplotlib plot horizontal line with label
• Matplotlib plot horizontal line on bar graph
• Matplotlib plot vertical line at date
• Matplotlib plot vertical line with text
• Matplotlib plot vertical line on histogram
• Matplotlib plot a linear function
• Matplotlib plot point on line graph
• Matplotlib scatter plot straight line
• Matplotlib plot line graph from dataframe
• Matplotlib plot a line in 3D