Matplotlib Line chart
Python hosting: Host, run, and code Python in the cloud!
A line chart can be created using the Matplotlib plot() function. While we can just plot a line, we are not limited to that. We can explicitly define the grid, the x and y axis scale and labels, title and display options.
Related course:
Line chart example
The example below will create a line chart.
from pylab import * |
Output:

The lines:
from pylab import * |
simply define the data to be plotted.
from pylab import * |
plots the chart. The other statements are very straightforward: statements xlabel() sets the x-axis text, ylabel() sets the y-axis text, title() sets the chart title and grid(True) simply turns on the grid.
If you want to save the plot to the disk, call the statement:
savefig("line_chart.png") |
Plot a custom Line Chart
If you want to plot using an array (list), you can execute this script:
from pylab import * |
The statement:
t = arange(0.0, 20.0, 1) |
defines start from 0, plot 20 items (length of our array) with steps of 1.
Output:

Multiple plots
If you want to plot multiple lines in one chart, simply call the plot() function multiple times. An example:
from pylab import * |
Output:

In case you want to plot them in different views in the same window you can use this:
import matplotlib.pyplot as plt |
Output:

The plt.subplot() statement is key here. The subplot() command specifies numrows, numcols and fignum.
Styling the plot
If you want thick lines or set the color, use:
plot(t, s, color="red", linewidth=2.5, linestyle="-") |
Leave a Reply: