Matplotlib Library in Python
Matplotlib Library in Python
Matplotlib
Data Visualization:
The process of finding trends and correlations in data by representing it pictorially is called Data
Visualization.
To perform data visualization in python, we can use various python data visualization modules such
as Matplotlib, Seaborn, Plotly, Ggplot.
What is Matplotlib:
➤ Matplotlib is a plotting library for the Python programming language and its numerical mathematics
extension NumPy.
Matplotlib Graphs:
1. Pairwise data: Plots of pairwise (x,y), tabular (var_0,...var_n), and functional f(x) = y data:
2. Statistical distributions: Plots of the distribution of at least one variable in a dataset. Some of
these methods also compute the distributions.
➤ Histogram: plt.hist(X)
3. Gridded data: Plots of arrays and images Z i,j and fields U i,j, Vi,j on regular grids and
corresponding coordinate grids X i,j , Y i,j
4. Irregularly gridded data: Plots of data Z x,y on unstructured grids, unstructured coordinate grids
(x,y) and 2D functions f(x,y) = z
5. 3D and volumetric data: Matplotlib also supports 3D plots using the mpl_toolkits.mplot3d library.
Install Matplotlib
Classes of Matplotlib:
1. Figure Class: This is the top-level container in this hierarchy. It is the overall window/page that
everything is drawn on. Syntax: import matplotlib.figure
2. Axes Class: This is what we commonly think of as 'a plot'. A given figure can contain many Axes,
but a given Axes object can only be in one Figure¹. The Axes contains two (or three in the case of
3D) Axis objects which take care of the data limits. Syntax: import matplotlib.axes
3. Axis Class: These are the number-line-like objects and take care of setting the graph limits and
generating the ticks (the marks on the axis) and ticklabels (strings labeling the ticks). Syntax:
import matplotlib.axis
4. Artist Class: Basically, everything visible on the figure is an artist (even the Figure, Axes, and Axis
objects). This includes Text objects, Line2D objects, collections objects, Patch objects. Syntax:
import matplotlib.artist
5. Pyplot: Pyplot is a Matplotlib module that provides a MATLAB-like interface. Pyplot provides
functions that interact with the figure i.e., creates a figure, decorates the plot with labels, etc.
Syntax: import matplotlib.pyplot
6. Backend Layer Classes: These include FigureCanvas (the surface on which the figure will be
drawn), Renderer (the class that takes care of drawing on the surface), and Event (handles mouse
and keyboard events). Syntax: import matplotlib
6
Import Matplotlib
4 rows × 25 columns
7
In [4]: # Getting the datatype of column
print(file.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 210 entries, 0 to 209
Data columns (total 25 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Not_AvailableME_of_Responder 210 non-null object
1 NUMBER_OF_MEMBERS_IN_HOUSEHOLD 210 non-null int64
2 AVG_HOUSEHOLD_INCOME 210 non-null int64
3 HOUSE_ADDRESS 210 non-null object
4 AGE_OF_MEMBERS 210 non-null object
5 MALE_MEMBERS 210 non-null int64
6 FEMALE_MEMBERS 210 non-null int64
7 NO_OF_CHILDREN 210 non-null int64
8 STUDYING_CHILDREN 210 non-null int64
9 NON_STUDYING_CHILDREN 210 non-null int64
10 FOOD_CONSUMPTION_PATTERNS 208 non-null object
11 EXPENDITURES 210 non-null int64
12 HOUSEHOLD_ASSETS 210 non-null object
13 Fridge 210 non-null object
14 AC 210 non-null object
15 Personal_Vehicle 210 non-null object
16 Washing_Machine 210 non-null object
17 TV 210 non-null object
18 SOURCES_OF_WATER 209 non-null object
19 AVAILABILITY_OF_SMART_DEVICES 210 non-null object
20 Desktop_Laptop 210 non-null object
21 Phone 210 non-null object
22 Other_SmartDevices 210 non-null object
23 ACCESS_TO_INTERNET 210 non-null object
24 ANY_PREDOMINANT_AILMENT 210 non-null object
dtypes: int64(8), object(17)
memory usage: 41.1+ KB
None
8
In [5]: #to check if the dataset has any missing value
file.isna().sum()
Out[5]: Not_AvailableME_of_Responder 0
NUMBER_OF_MEMBERS_IN_HOUSEHOLD 0
AVG_HOUSEHOLD_INCOME 0
HOUSE_ADDRESS 0
AGE_OF_MEMBERS 0
MALE_MEMBERS 0
FEMALE_MEMBERS 0
NO_OF_CHILDREN 0
STUDYING_CHILDREN 0
NON_STUDYING_CHILDREN 0
FOOD_CONSUMPTION_PATTERNS 2
EXPENDITURES 0
HOUSEHOLD_ASSETS 0
Fridge 0
AC 0
Personal_Vehicle 0
Washing_Machine 0
TV 0
SOURCES_OF_WATER 1
AVAILABILITY_OF_SMART_DEVICES 0
Desktop_Laptop 0
Phone 0
Other_SmartDevices 0
ACCESS_TO_INTERNET 0
ANY_PREDOMINANT_AILMENT 0
dtype: int64
2 88
1 65
3 36
4 9
0 7
5 4
6 1
Name: MALE_MEMBERS, dtype: int64
88
Wagon
1 2 Maruti Hatchback Petrol Manual 998 20.5 40005 2
R
Wagon
2 3 Maruti Hatchback Petrol Manual 998 20.5 40005 2
R
Here are some of the functions in matplotlib.pyplot that are used to set properties and
customizing the appearance of plot:
Line Plot
1. args: This is a variable length argument, allowing for multiple x, y pairs with an optional format
string.
2. scalex, scaley: These are optional boolean values that, when set to True (default), will autoscale
the x and/or y axis.
3. data: This is an optional parameter where you can pass a DataFrame.
4. color: color or list of color, optional. The colors of the line faces.
5. linewidth: float or array-like, optional. Width of the line edges.
6. label: str or list of str, optional. A label for the whole dataset or individual lines.
10
In [10]: fig = plt.figure(figsize=(3, 2), dpi=150)
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
plt.plot(name, marks,
color = 'y',
label = 'Marks',
linewidth = 4,
scalex=True, # If, it's falese x axis line will not visible, by default it's
scaley=True) # If, it's falese x axis line will not visible, by default it's
plt.legend()
Scatter Plot
1. x, y: These are arrays or sequences of n numbers representing the data positions. This defines dot
size
2. s: This is the marker size in points**2. It can be a scalar or an array-like shape (n,), and is optional.
3. c or color: This represents the marker colors. It can be an array-like or list of colors or color, and is
optional.
4. marker: This is the marker style. It can be either an instance of the class or the text shorthand for a
particular marker.
5. cmap: This is the Colormap instance or registered colormap name used to map scalar data to
colors.
6. norm: This is the normalization method used to scale scalar data to the [0, 1] range before mapping
to colors using cmap.
7. vmin, vmax: These are used in conjunction with norm to normalize luminance data.
8. alpha: This is the alpha blending value, between 0 (transparent) and 1 (opaque).
9. linewidths: This is the linewidth of the marker edges.
10. edgecolors: This is the color or sequence of colors of the marker edges.
11. plotnonfinite: This boolean value is used to indicate whether to plot the non-finite x, y values.
12. data: This is an optional parameter that can be a DataFrame.
16
In [16]: fig = plt.figure(figsize=(3, 2), dpi=150)
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
plt.scatter(name, marks)
Out[16]: <matplotlib.collections.PathCollection at 0x7931c34e3040>
17
In [17]: # Using the parameters of plt.scatter()
fig = plt.figure(figsize=(3, 2), dpi=150)
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
c = ['r', 'g', 'b']# pass tuple or list for color
plt.scatter(name, marks,
color = c,
s = 80, # Can also pass a specific color
marker='*', # ‘o’ for a circle, ‘s’ for a square, ‘*’ for a star marker, etc
alpha = 0.6,
edgecolor = 'black',
linewidth = 2,
plotnonfinite=True) # not that much imp
plt.colorbar()
Out[17]: <matplotlib.colorbar.Colorbar at 0x7931c3562f50>
18
In [18]: # Using vmin, vmax and norm parameter
import matplotlib.colors as mcolors
fig = plt.figure(figsize=(3, 2), dpi=150)
N = 40
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
n = mcolors.Normalize(vmin=-2.,vmax=2.) # We have to use, mcolors to use, vmin and vm
plt.scatter(x, y, c=colors, norm=n, cmap='viridis') # In cmap we have huge color comb
plt.colorbar()
plt.show()
19
In [19]: # Using data parameter
fig = plt.figure(figsize=(3, 2), dpi=150)
df = pd.DataFrame({
'a': np.random.randn(1000),
'b': np.random.randn(1000),
'c': np.random.randn(1000)
})
plt.scatter('a', 'b', c='c', data=df) # The x and y coordinates of the points are the
# and the colors of the points are specified by
plt.show()
Stem Plot
plt.fill_between(x, y1, y2)/ plt.plot(x,y) plt.fill_between(), where x and y can be list or tuple
1. x: An array of length N representing the x-coordinates of the nodes defining the curves.
2. y1: An array of length N or a scalar representing the y-coordinates of the nodes defining the first
curve.
3. y2: An array of length N or a scalar (default: 0) representing the y-coordinates of the nodes defining
the second curve.
4. color: Color or array-like of color, default: None.
5. where: An array of boolean values of length N (optional) used to exclude some horizontal regions
from being filled.
6. interpolate: An optional boolean parameter (default: False) that is relevant if where is used and the
two curves are crossing each other.
7. step: An optional parameter that accepts one of the three values: 'pre', 'post', or 'mid'. It specifies
where the steps will occur.
31
In [34]: fig = plt.figure(figsize=(3, 2), dpi=150)
# Filled area between
sub = ["Machine Learning", "Maths", "Deep Learning", "NLP"]
std1 = [92, 88, 60, 72]
plt.plot(sub, std1)
plt.fill_between(sub, std1)
Out[34]: <matplotlib.collections.PolyCollection at 0x7931c1718670>
The baseline parameter is used to denote the method used to calculate the baseline:
2. Statistical distributions
Histogram:
plt.hist(x)
1. x: This is the sequence of data that you want to plot in the histogram.
2. bins: This can be an integer, sequence, or string. If an integer, it defines the number of equal-width
bins in the range. If a sequence, it defines the bin edges.
3. range: This is the lower and upper range of the bins.
4. density: If True, the function will draw and return a probability density.
5. weights: This is an array of weights, of the same shape as x.
6. cumulative: If True, then a histogram is computed where each bin gives the counts in that bin plus
all bins for smaller values.
7. bottom: This is the location of the bottom baseline of each bin.
8. histtype: This parameter is used to draw type of histogram. Options include ‘bar’, ‘barstacked’,
‘step’, 'stepfilled’.
9. align: This controls how the histogram is plotted. Options include ‘left’, ‘mid’, 'right’.
10. orientation: This controls the orientation of the histogram. Options include ‘horizontal’, 'vertical’.
11. rwidth: This is the relative width of the bars as a fraction of the bin width.
12. log: If True, the histogram axis is set to a log scale.
13. edgecolors: This is the color or sequence of colors of the marker edges.
14. color: This is a color spec or sequence of color specs, one per dataset.
15. label: This is a string, or sequence of strings to match multiple datasets.
16. stacked: If True, multiple data are stacked on top of each other If false multiple data are arranged 39
side by side if histtype is ‘bar’ or on top of each other if histtype is 'step’.
17. data: This parameter is used when the x values are a string, in which case this should be a data
object that the string can be looked up in.
Box plot:
plt.boxplot(X)
Violin Plot:
plt.violinplot(D)
47
In [54]: # Create data
data = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]]
# Create violin plot
plt.violinplot(data)
Out[54]: {'bodies': [<matplotlib.collections.PolyCollection at 0x7931c1625db0>,
<matplotlib.collections.PolyCollection at 0x7931c0fa2710>,
<matplotlib.collections.PolyCollection at 0x7931c0fa2a70>,
<matplotlib.collections.PolyCollection at 0x7931c0fa2dd0>],
'cmaxes': <matplotlib.collections.LineCollection at 0x7931c1168220>,
'cmins': <matplotlib.collections.LineCollection at 0x7931c0fa3430>,
'cbars': <matplotlib.collections.LineCollection at 0x7931c0fa3820>}
Hist 2D:
plt.hist2D(x, y)
48
In [55]: # Create data
np.random.seed(0)
x = np.random.normal(0, 1, 1000)
y = np.random.normal(0, 1, 1000)
# Create 2D histogram
plt.hist2d(x, y, bins=(50, 50), cmap=plt.cm.jet)
plt.colorbar()
Out[55]: <matplotlib.colorbar.Colorbar at 0x7931c102b460>
Hexbin:
plt.hexbin(x, y)
49
In [56]: import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8]
y = [1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8]
# Create a hexbin plot
plt.hexbin(x, y, gridsize=30, cmap='Greens')
# Add a colorbar for reference
plt.colorbar()
# Show the plot
plt.show()
Pie Plot
In [57]: plt.pie([1])
plt.show()
51
In [58]: # Number of memberss in household showing through pie chart and percentage
plt.figure(1, figsize=(4,4))
label=file.MALE_MEMBERS.value_counts().index # Use value_counts to get the frequency
count=file.MALE_MEMBERS.value_counts().values # Use value_counts to get the frequency
plt.pie(count, labels=label)
plt.show()
52
In [59]: # Using the parameters inside plt.pie() graph
plt.figure(1, figsize=(6,6))
label=file.MALE_MEMBERS.value_counts().index
count=file.MALE_MEMBERS.value_counts().values
plt.title("Male members in the household", fontsize = 15, fontweight ="bold")
ex =[0.2, 0.1, 0, 0, 0, 0, 0]
co = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
plt.pie(count,
explode= ex,
labels= label,
colors= co,
autopct= '%0.2f%%',
pctdistance= 0.85,
labeldistance= 1.2,
shadow= True,
startangle= 140,
radius= 4, # By default it's 1
counterclock= True,
wedgeprops={'linewidth': 2, 'edgecolor': 'black'}, # This is a dictionary of
textprops={'fontsize': 14}, # This is a dictionary of arguments. For example,
center=(2, 3), # The default value is (0, 0). For example, center = (2, 3) se
frame = True,
rotatelabels = True)
plt.legend(loc = 'upper right')
plt.show()
53
In [60]: # Number of memberss in household showing through donout chart and percentage
# We can also create donout chart, through plt.gca().add_artist
plt.figure(1, figsize=(4,4))
label=file.FEMALE_MEMBERS.value_counts().index # Use value_counts to get the frequency
count=file.FEMALE_MEMBERS.value_counts().values # Use value_counts to get the frequen
plt.pie(count, labels=label, radius = 1.2)
plt.pie([1], colors = 'w', radius = 0.6)
plt.show()
54
In [61]: # Creating multiple pie graph in a chart
plt.figure(1, figsize=(4,4))
label= file.MALE_MEMBERS.value_counts().index
male= file.MALE_MEMBERS.value_counts().values
female= file.FEMALE_MEMBERS.value_counts().values
co = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
plt.pie(male, labels=label, radius = 1.2)
plt.pie(female, labels=label, radius = 0.8, colors = co)
plt.show()
3. Gridded data
plt.imshow(Z)
<class 'numpy.ndarray'>
(360, 544, 3)
56
In [63]: # Printing a cmap image
# In cmapscale, we can only print 2D image, so first we have to convert it into 2D
gray_robo = robo[:, :, 0]
plt.imshow(gray_robo)
plt.colorbar()
plt.rcParams['figure.figsize'] # Getting default image size
Out[63]: [6.4, 4.8]
57
In [64]: # Showing image in different colors
color_robo = plt.imread('/content/drive/MyDrive/ML and DL DataSets/3.1_Robo_img.jpg')
robo_2D = color_robo[:, :, 0] # Converting into 2D array, to use it in cmap
fig, axes = plt.subplots(nrows = 2, ncols = 3, figsize = plt.figaspect(1/2)) # Figas
map = ['plasma', 'Wistia', 'gray', 'magma', 'jet', 'inferno']
for i, cmap in zip(axes.flat, map):
i.imshow(robo_2D, cmap = cmap)
i.set(title = cmap)
i.axis('off')
plt.show()
Contour plot:
1. X, Y: These are array-like and optional. They represent the coordinates of the values in Z. X and Y
must both be 2D with the same shape as Z (e.g., created via numpy.meshgrid).
2. Z: This is an array-like parameter that represents the height values over which the contour is drawn.
Color-mapping is controlled by cmap, norm, vmin, and vmax.
3. levels: This is an optional parameter that determines the number and positions of the contour
lines/regions.
4. corner_mask: This is a boolean parameter that enables/disables corner masking, which only has
an effect if Z is a masked array.
5. colors: This is an optional parameter that represents the colors of the levels, i.e., the lines for 63
contour.
6. alpha: This is an optional parameter that represents the alpha blending value, between 0
(transparent) and 1 (opaque).
7. vmin, vmax: These parameter are optional in nature and they are colorbar range.
8. cmap: This is an optional parameter that represents the Colormap instance or registered colormap
name used to map scalar data to colors.
9. linewidths: This parameter is used to specify the line width of the contour lines.
10. linestyles: This parameter is used to specify the style of the contour lines.
11. norm: This is an optional parameter that represents the normalization method used to scale scalar
data to the [0, 1] range before mapping to colors using cmap.
Parameter in plt.contour() and plt.contourf() are almost same, there is no major differance.
Only, cntourf will help to fill the area.
66
In [75]: fig = plt.figure(figsize=(4, 2), dpi=150)
# Create a 2D array with random values
Z = np.random.random((10,10))
# Display the array
plt.contourf(Z)
Out[75]: <matplotlib.contour.QuadContourSet at 0x7931c08ae200>
Streamplot:
plt.streamplot(X, Y, U, V)
68
In [78]: fig = plt.figure(figsize=(4, 3), dpi=150)
# Create a grid of points
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
# Create a simple vector field: a vortex centered at the origin
U = -Y
V = X
# Create a stream plot
plt.streamplot(X, Y, U, V, density=2, linewidth=1, arrowsize=1, cmap='viridis')
Out[78]: <matplotlib.streamplot.StreamplotSet at 0x7931c040e530>
Scatter 3D Plot:
ax.scatter(x, y, z), Here only numerical value will support. X, Y and Z can be, list, tuple or array
1. xs, ys, zs: These are arrays or sequences of n numbers representing the data positions in the x, y,
and z dimensions respectively.
2. s: This is the marker size in points**2. It can be a single value for all markers or a sequence of
values for each marker individually.
3. c: This is the marker color. It can be a single color format string, a sequence of color specifications
of length n, or a sequence of n numbers to be mapped to colors using the cmap and norm
parameters.
4. depthshade: This is a boolean value that determines whether or not to shade the scatter markers
to give the appearance of depth. Default is True.
70
In [80]: ax_eda = plt.axes(projection = '3d') # We have to specify this in every cell. Otherwi
x = file.MALE_MEMBERS.value_counts().values
y = file.FEMALE_MEMBERS.value_counts().values
num = [0, 1, 2, 3, 4, 5, 6]
ax_eda.scatter (x, y, num)
Out[80]: <mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x7931c0e554e0>
71
In [81]: #3d plotting of Year and Buyers wrt Price
fig = plt.figure()
ax_car = fig.add_subplot(111 , projection = '3d') # 111 argument is a 3-digit integer
# the second the number of columns,
x = df_car[['Year']]
y = df_car[['Buyers']]
z = df_car[['Price (Lakhs)']]
# Giving the label
ax_car.set_xlabel ('Year')
ax_car.set_ylabel ('Buyers')
ax_car.set_zlabel ('Price')
# Scatter plotting of graph
ax_car.scatter (x,y,z)
Plot Surface:
plot_surface(X, Y, Z)
73
In [83]: # Create a figure
fig = plt.figure()
# Create a 3D plot
ax = fig.add_subplot(111, projection='3d')
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
x, y = np.meshgrid(x, y) # We have to use this otherwise, it will throw error: 'list'
z = x+y
# Plot the data
ax.plot_surface(x, y, z)
ax.set_facecolor("#a5cf97") # For bckground color
74
In [84]: fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y) # ‘list’ object has no attribute ‘ndim’ typically occurs whe
# instead. The .ndim attribute is used to get the number of
z = np.sin(np.sqrt(x**2 + y**2))
ax.plot_surface(x, y, z, cmap='inferno')
ax.set_facecolor("#1CC4AF")
75
In [85]: #3d plotting of Year and Buyers wrt Price
fig = plt.figure()
ax_car = fig.add_subplot(111 , projection = '3d') # 111 argument is a 3-digit integer
# the second the number of columns,
x = df_car[['Year']]
y = df_car[['Buyers']]
x, y = np.meshgrid(x, y) # meshgrid function is used to create a rectangular grid out
z = df_car[['Price (Lakhs)']]
# Giving the label
ax_car.set_xlabel ('Year')
ax_car.set_ylabel ('Buyers')
ax_car.set_zlabel ('Price')
ax_car.plot_surface (x,y,z, cmap='plasma')
Voxels 3D:
Plot Wireframe:
plot_wireframe(X, Y, Z)
77
In [87]: # Create a figure
fig = plt.figure()
# Create a 3D plot
ax = fig.add_subplot(111, projection='3d')
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
x, y = np.meshgrid(x, y) # We have to use this otherwise, it will throw error: 'list'
z = x+y
# Plot the data
ax.plot_wireframe(x, y, z)
ax.set_facecolor("#e09696")
78
In [88]: fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
ax.plot_wireframe(x, y, z, color='orange')
ax.set_facecolor("#bdb184")
79
In [89]: #3d plotting of Year and Buyers wrt Price
fig = plt.figure()
ax_car = fig.add_subplot(111 , projection = '3d')
x = df_car[['Year']]
y = df_car[['Buyers']]
x, y = np.meshgrid(x, y)
z = df_car[['Price (Lakhs)']]
# Giving the label
ax_car.set_xlabel ('Year')
ax_car.set_ylabel ('Buyers')
ax_car.set_zlabel ('Price')
ax_car.plot_wireframe(x,y,z)
Out[89]: <mpl_toolkits.mplot3d.art3d.Line3DCollection at 0x7931c004b460>
Subplot
Graph Saving
plt.savefig(file_name)
82
In [92]: fig = plt.figure(figsize=(3,2), dpi=150)
# Can save 2d and 3d plot
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
plt.plot(name, marks)
plt.savefig("Sample.pdf", # It will save in pdf format, by default it's png
dpi = 2000, # It will increase the resolution
facecolor = 'g', # It will set a padding in the chart
transparent = True,
bbox_inches = 'tight') # It will reduce the padding size
Axis in Matplotlib
83
In [93]: fig = plt.figure(figsize=(3,2), dpi=150)
# Adding labels in plot
name = (1, 2, 3)
marks = [96, 80, 60]
plt.xticks(name, labels = ['Subha', 'Subhajit Das', 'Subhajit'])
plt.yticks(marks)
plt.bar(name, marks)
Out[93]: <BarContainer object of 3 artists>
84
In [94]: fig = plt.figure(figsize=(3,2), dpi=150)
# Specify limit in plot
name = (1, 2, 3)
marks = [96, 80, 60]
plt.xticks(name, labels = ['Subha', 'Subhajit Das', 'Subhajit'])
plt.yticks(marks)
plt.xlim(0,2)
plt.ylim(45,100)
plt.bar(name, marks, color = 'orange')
Out[94]: <BarContainer object of 3 artists>
Text in Matplotlib
85
In [95]: fig = plt.figure(figsize=(3, 2), dpi=150)
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
plt.title("Student Marks", fontsize = 12)
plt.xlabel("Names", fontsize = 12)
plt.ylabel("Marks", fontsize = 12)
plt.text(0,88,"Calculas", # row position, column position, text
fontsize = 8,
style = 'italic',
bbox = {'facecolor' : 'green'})
plt.annotate("Deep Learning", xy=(1,76), # text, arrow position
xytext = (0.5, 60), # text position
arrowprops = dict(facecolor = 'black', shrink = 0.1)) # arrow color, arr
plt.scatter(name, marks, label = 'Marks')
plt.legend(loc = 1,
facecolor = 'orange',
edgecolor = 'red',
framealpha = 0.8,
shadow = True)
Out[95]: <matplotlib.legend.Legend at 0x7931be390b80>