In this article:
1. Plotting more sets of data in the same graph
Lets plot two functions
y1=x2 + 1, y2= x3+2*t
X values are between 0 and 10
Code which solve the problem:
import numpy as np
import matplotlib.pyplot as myplot
t = np.arange(0., 10., 0.25)
myplot.plot( t, t**2+1, 'r>') myplot.plot( t, t**3+2*t, 'b*')
myplot.show()
Code explanation:
t = np.arange(0., 10., 0.25)
this generate x coordinate values. First argument 0. is the start value.
Second argument 10. is the end value. Third argument is the step between value.
Means generated values by np.arange are 0., 0.25, 0.50, 0.75, 1, 1.25 etc.
Plot function have 3 arguments this time, first two was explained in previous post.
Third argument is plot "format string", which describe colour used for draw and character.
Thus for myplot.plot( t, t**2+1, 'r>')
third argument 'r>' will draw plot in red colour ('r') using triangle_right marker ('>).
Documentation about all markers supported by plot are in matplotlib.pyplot.plot, section "Format Strings".
Is important to retain that in plot "format string" first character is plot colour and the second character is type of marker.
For myplot.plot( t, t*3+2t, 'b') third argument 'b' will draw plot in blue ('b') and the marker is '*'
Output from code is in below image:
2. A graph with categorical variables
Sample problem for this case: we have population
spread in 4 group ages:
years_18_30, medium income is 2800
years_31_45, medium income is 4100
years_46_60, medium income is 4500
years_60_plus, medium income is 3800
We need to plot categorical variable age/income for this.
Code is:
import matplotlib.pyplot as myplot
ages=['year_18_30', 'year_31_45', 'year_46_60', 'year_60_plus']
income = [2800, 4100, 4500, 3800]
myplot.figure(figsize=(5, 5))
myplot.subplot(111)
myplot.bar(ages, income)
myplot.show()
This time graph is draw in a figure, created by
myplot.figure(figsize=(5, 5))
Size of figure is width 5 inches, heigh 5 inches.
Graph is a bar graph type, draw with
myplot.bar(ages, income)
In code Similar output we used figure and subplot, similar output is obtained
without those with code:
import matplotlib.pyplot as myplot
ages=['year_18_30', 'year_31_45', 'year_46_60', 'year_60_plus']
income = [2800, 4100, 4500, 3800]
myplot.bar(ages, income)
myplot.show()