Mat Plot Lib
Mat Plot Lib
• Whenever you plot with matplotlib, the two main code lines should be
considered:
– Type of graph
• this is where you define a bar chart, line chart, etc.
– Show the graph
• this is to display the graph
E.g. Matplotlib
• Matplotlib allows you to make easy things
• You can generate plots, histograms, power
spectra, bar charts, errorcharts, scatterplots,
etc., with just a few lines of code.
Line Graphs
import matplotlib.pyplot as plt
plt.plot(x, y1)
plt.plot(x, y2)
plt.xlabel("x")
plt.ylabel("y") Incrementally
plt.ylim(-2000, 2000) modify the figure.
plt.axhline(0) # horizontal line
plt.axvline(0) # vertical line
plt.savefig("quad.png")
Save your figure to a file
plt.show() Show it on the screen
Plot
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)
no return value?
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
# line 2 points
x2 = [1,2,3]
y2 = [4,1,3]
# plotting the line 2 points
plt.plot(x2, y2, label = "line 2")
# heights of bars
height = [10, 24, 36, 40, 5]
# labels for bars
names = ['one','two','three','four','five']
# frequencies
ages=[2,5,70,40,30,45,50,45,43,40,44,60,7,13,57,18,90,77,32,21,20,40]
# plotting a histogram
plt.hist(ages, bins, range, color='green',histtype='bar',rwidth=0.8)
# x-axis label
plt.xlabel('age')
# frequency label
plt.ylabel('No. of people')
# plot title
plt.title('My histogram')
x_values = [0,1,2,3,4,5]
y_values = [0,1,4,9,16,25]
# x-axis values
x = [1,2,3,4,5,6,7,8,9,10]
# y-axis values
y = [2,4,5,7,6,8,9,11,12,12]
# x-axis label
plt.xlabel('x - axis')
# frequency label
plt.ylabel('y - axis')
# plot title
plt.title('My scatter plot!')
# showing legend
plt.legend()
# defining labels
activities = ['eat', 'sleep', 'work', 'play']
# plotting legend
plt.legend()