Introduction Data Visualization
Introduction Data Visualization
Overview of Matplotlib
1
Introduction
• Matplotlib is probably the most popular plotting library for
Python.
• Each plot is encapsulated in a Figure object. Which is the
top-level container of the visualization. It can have multiple
axes.
• The two main components of a plot are as follows:
– Axes :It is the actual plot, or subplot, depending on whether you want
to plot single or multiple visualizations. Its sub-objects include the x
and y axis, spines, and legends.
2
Introduction
3
Introduction
4
Plotting Basics
• We will use pyplot submodule of matplotlib
• Steps for using pyplot
– import matplotlib.pyplot as plt
– plt.figure() # for creating figure
– plt.figure(figsize=(10, 5))# to change width and height
default values (6.4&4.8 inch)
• If you want to close specified figure, you must give figure a number
– plt.figure(num=10)
– plt.close(10)
• You can use this command to find figure number:
plt.gcf().number
5
Plotting Basics
• Format strings
– It is specified as “[color] [marker] [line]”
• We can specify color in either of these formats
– RGB or RGBA float tuples (for example, (0.2, 0.4, 0.3) or (0.2, 0.4, 0.3, 0.5))
– RGB or RGBA hex strings (for example, '#0F0F0F' or '#0F0F0F0F’)
6
Plotting Basics
For representing markers
7
Plotting Basics
For representing different types of lines
8
Plotting Basics
• General format of plot function
– import matplotlib.pyplot as plt
– plt.plot([x],y,[fmt])# x optional
– plt.plot([0, 1, 2, 3], [2, 4, 6, 8])# produces solid
st.line
–
9
Creating Simple Visualization
• We want to create this plot
Notes:
Extra Features:
1)Add inline command after import :
1) Add features to line
%matplotlib inline
2) Draw another line on same
figure
2) After creating plot call plt.show() to
3) Save figure
show the figure
10
Text functions
• Functions for setting labels for x axis and y axis
– plt.xlabel() , plt.ylabel() # set labels for current axes (plot)
– set_xlabel() , set_ylabel() # set labels for specified axes (plot)
• Example:
• Fig,ax=plot.subplots()
• ax.plot([1,2,3,4])
• ax.setxlabel(‘X Label’)
11
Text functions
• Functions for adding text
– figtext(x,y,text) # add text for figure
– text (x,y,text) # add text for certain axes
12
Text functions
ax.text(4, 6, 'Text in Data Coords', bbox={'facecolor': 'yellow', 'alpha':0.5, 'pad':10})
13
Text functions
• Functions for adding legend
– plt.legend () # for current axes
– ax.legend() # for spec axes
– plt.plot([1, 2, 3], label='Label 1')
– plt.plot([2, 4, 3], label='Label 2')
– plt.legend()
14
Ex: Visualization of stock trends
15