Basic Charts in Python
Basic Charts in Python
- Line Chart
- Bar Chart
- Pie Chart
Matplotlib is a 2D plotting library which can be
used to generate publication quality figures.
Matplotlib
Line chart
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.
from pylab import *
t = arange(0.0, 2.0,
0.01)
s = sin(2.5*pi*t)
plot(t, s)
xlabel('time (s)')
ylabel('voltage
(mV)')
title('Sine Wave')
grid(True)
show()
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 *
t = arange(0.0,
20.0, 1)
s =
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
plot(t, s)
xlabel('Item (s)')
ylabel('Value')
title('Python Line
Chart: Plotting numbers')
grid(True)
show()
If you want to plot multiple lines in one chart,
simply call the plot() function multiple times.
In case you want to plot them in different views
in the same window you can use this:
import
matplotlib.pyplot as plt
from pylab import *
t = arange(0.0,
20.0, 1)
s =
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
s2 =
[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
plt.subplot(2, 1, 1)
plt.plot(t, s)
plt.ylabel('Value')
plt.title('First
chart')
plt.grid(True)
plt.subplot(2, 1, 2)
plt.plot(t, s2)
plt.xlabel('Item
(s)')
plt.ylabel('Value')
plt.title('Second
chart')
plt.grid(True)
plt.show()
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="-")
Matplotlib Bar chart
import
matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import
matplotlib.pyplot as plt
objects = ('Python',
'C++', 'Java', 'Perl', 'Scala', 'Lisp')
y_pos =
np.arange(len(objects))
performance =
[10,8,6,4,2,1]
plt.bar(y_pos,
performance, align='center', alpha=0.5)
plt.xticks(y_pos,
objects)
plt.ylabel('Usage')
plt.title('Programming
language usage')
plt.show()
Matplotlib charts can be
horizontal, to create a horizontal bar chart:
plt.yticks(y_pos,
objects)
plt.xlabel('Usage')
You can compare two data series using this Matplotlib code:
import numpy as np
import
matplotlib.pyplot as plt
# data to plot
n_groups = 4
means_frank = (90,
55, 40, 65)
means_guido = (85,
62, 54, 20)
# create plot
fig, ax =
plt.subplots()
index =
np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
rects1 =
plt.bar(index, means_frank, bar_width,
alpha=opacity,
color='b',
label='Frank')
rects2 =
plt.bar(index + bar_width, means_guido, bar_width,
alpha=opacity,
color='g',
label='Guido')
plt.xlabel('Person')
plt.ylabel('Scores')
plt.title('Scores by
person')
plt.xticks(index +
bar_width, ('A', 'B', 'C', 'D'))
plt.legend()
plt.tight_layout()
plt.show()
Matplotlib supports pie charts
using the pie() function.
import
matplotlib.pyplot as plt
# Data to plot
labels = 'Python',
'C++', 'Ruby', 'Java'
sizes = [215, 130,
245, 210]
colors = ['gold',
'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0,
0, 0) # explode 1st slice
# Plot
plt.pie(sizes,
explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True,
startangle=140)
plt.axis('equal')
plt.show()
To
add a legend use the plt.legend() function:
import
matplotlib.pyplot as plt
labels
= ['Cookies', 'Jellybean', 'Milkshake', 'Cheesecake']
sizes
= [38.4, 40.6, 20.7, 10.3]
colors
= ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
patches,
texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90)
plt.legend(patches,
labels, loc="best")
plt.axis('equal')
plt.tight_layout()
plt.show()
Comments
Post a Comment