MatPlotLib With Python - DATAhill Solutions
MatPlotLib With Python - DATAhill Solutions
in
MatPlotLib:
Matplotlib is a plotting library for Python.
It is used along with NumPy to provide an environment that is an
effective open source alternative for MatLab.
Matplotlib module was first written by John D. Hunter
plt.plot([1,2,3,4],[10,20,30,40])
plt.show()
plt.plot([1,2,3,4],[10,20,30,40])
plt.title("Sales Plot")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
We can also specify the size of the figure using method figure() and
passing the values as a tuple of the length of rows and columns to the
argument figsize
plt.figure(figsize=(15,5))
plt.plot([1,2,3,4],[10,20,30,40])
plt.show()
^ Triangle_up marker
< Triangle_left marker
> Triangle_right marker
1 Tri_down marker
2 Tri_up marker
3 Tri_left marker
4 Tri_right marker
s Square marker
p Pentagon marker
* Star marker
h Hexagon1 marker
H Hexagon2 marker
+ Plus marker
x X marker
D Diamond marker
d Thin_diamond marker
| Vline marker
_ Hline marker
r Red
c Cyan
m Magenta
y Yellow
k Black
w White
With every X and Y argument, you can also pass an optional third
argument in the form of a string which indicates the colour and line type
of the plot.
The default format is b- which means a solid blue line.
Likewise, we can make many such combinations to format our plot.
plt.plot([1,2,3,4],[10,20,30,40],"go")
plt.title("Sales Plot")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
x = np.arange(1,5)
y = x**5
plt.plot([1,2,3,4],[10,20,30,40],"go",x,y,"r^")
plt.title("Sales Plot")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
Bar Graphs
===========
Bar graphs are one of the most common types of graphs and are used
to show data associated with the categorical variables.
Pyplot provides a method bar() to make bar graphs which take
arguments: categorical variables, their values and color (if you want to
specify any).
month = ["Jan","Feb","Mar","Apr","May"]
sales = [50,60,55,75,65]
plt.bar(month,sales,color="green")
plt.title("Bar Graph")
plt.xlabel("Months")
plt.ylabel("Sales")
plt.show()
To create horizontally stacked bar graphs we use the bar() method twice
and pass the arguments where we mention the index and width of our
bar graphs in order to horizontally stack them together.
Also, notice the use of two other methods legend() which is used to
show the legend of the graph and xticks() to label our x-axis based on
the position of our bars.
month = ["Jan","Feb","Mar","Apr","May"]
HYDsales = [50,60,55,75,65]
BNGsales = [55,50,70,60,80]
index = np.arange(5)
width = 0.30
plt.bar(index,HYDsales,width,color="green",label="Hyd Sales")
plt.bar(index+width,BNGsales,width,color="blue",label="Bang Sales")
plt.title("Horizontally Stacked Bar Graphs")
plt.xlabel("Months")
plt.ylabel("Sales")
plt.xticks(index+ width/2, month)
plt.legend(loc="best")
plt.show()
plt.bar(index,HYDsales,width,color="blue",label="Hyd Sales")
plt.bar(index,BNGsales,width,color="red",label="Bang
Sales",bottom=HYDsales)
plt.title("Vertically Stacked Bar Graphs")
plt.xlabel("Months")
plt.ylabel("Sales")
plt.xticks(index, month)
plt.legend(loc="best")
plt.show()
Pie Charts
==========
One more basic type of chart is a Pie chart which can be made using the
method pie() We can also pass in arguments to customize our Pie chart
to show shadow, explode a part of it, tilt it at an angle as follows:
month = ["Jan","Feb","Mar","Apr","May"]
sales = [50,60,55,75,65]
e = [0,0.1,0,0,0]
plt.pie(sales,explode=e,labels=month,shadow=True,startangle=45)
plt.axis("equal")
plt.legend(title="Sales Graph")
plt.show()
Histogram
=========
Histograms are a very common type of plots when we are looking at
data like height and weight, stock prices, waiting time for a customer, etc
which are continuous in nature.
Histogram’s data is plotted within a range against its frequency.
Histograms are very commonly occurring graphs in probability and
statistics and form the basis for various distributions like the normal -
distribution, t-distribution, etc.
x = np.random.randn(1000)
plt.title("Histogram")
plt.xlabel("Random Data")
plt.ylabel("Frequency")
plt.hist(x,10)
plt.show()
height =
np.array([130,135,120,145,165,175,180,145,150,160,140,170,165,135,1
55])
weight = np.array([60,70,65,75,80,90,95,85,70,78,88,72,68,77,88])
plt.xlim(100,200)
plt.ylim(50,100)
plt.scatter(height,weight)
plt.title("Scatter Plot")
plt.xlabel("Height")
plt.ylabel("Weight")
plt.show()
ax = plt.axes(projection="3d")
ax.scatter3D(height,weight)
ax.set_xlabel("Height")
ax.set_ylabel("Weight")
plt.show()
We can also create 3-D graphs of other types like line graph, surface,
wireframes, contours, etc.
The above example in the form of a simple line graph is as follows: Here
instead of scatter3D() we use method plot3D()
ax = plt.axes(projection="3d")
ax.plot3D(height,weight)
ax.set_xlabel("Height")
ax.set_ylabel("Weight")
plt.show()
plt.subplot(1,2,1)
plt.plot([1,2,3,4],[10,20,30,40],"go")
plt.title("1st subplot")
plt.subplot(1,2,2)
x = np.arange(1,5)
y = x**5
plt.plot(x,y,"r^")
plt.title("2nd subplot")
plt.suptitle("Sales Plots")
plt.show()
If we want our sub-plots in two rows and single column, we can pass
arguments (2,1,1) and (2,1,2)
plt.subplot(2,1,1)
plt.plot([1,2,3,4],[10,20,30,40],"go")
plt.title("1st subplot")
plt.subplot(2,1,2)
x = np.arange(1,5)
y = x**5
plt.plot(x,y,"r^")
plt.title("2nd subplot")
plt.suptitle("Sales Plots")
plt.show()
x = np.arange(1,5)
y = x**5
fig, ax = plt.subplots(nrows=2,ncols=2,figsize=(6,6))
ax[0,1].plot([1,2,3,4],[10,20,30,40],"go")
ax[1,0].plot(x,y,'r^')
ax[0,1].set_title("Squares")
ax[1,0].set_title("Cubes")
plt.show()
Summary:
========
plot(x-axis values, y-axis values) — plots a simple line graph with x-axis
values against y-axis values
show() — displays the graph
title(“string”) — set the title of the plot as specified by the string
xlabel(“string”) — set the label for x-axis as specified by the string
ylabel(“string”) — set the label for y-axis as specified by the string
figure() — used to control a figure level attributes
subplot(nrows, ncols, index) — Add a subplot to the current figure
suptitle(“string”) — It adds a common title to the figure specified by the
string
subplots(nrows, ncols, figsize) — a convenient way to create subplots, in
a single call. It returns a tuple of a figure and number of axes.
set_title(“string”) — an axes level method used to set the title of subplots
in a figure
bar(categorical variables, values, color) — used to create vertical bar
graphs
barh(categorical variables, values, color) — used to create horizontal bar
graphs
legend(loc) — used to make legend of the graph