Matplotlib: Python Data Visualization Guide
Matplotlib: Python Data Visualization Guide
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: [Link](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 [Link]
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 [Link]
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 [Link]
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 [Link]
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 [Link]
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([Link]())
<class '[Link]'>
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
[Link]().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 [Link] 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 = [Link](figsize=(3, 2), dpi=150)
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
[Link](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
[Link]()
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 = [Link](figsize=(3, 2), dpi=150)
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
[Link](name, marks)
Out[16]: <[Link] at 0x7931c34e3040>
17
In [17]: # Using the parameters of [Link]()
fig = [Link](figsize=(3, 2), dpi=150)
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
c = ['r', 'g', 'b']# pass tuple or list for color
[Link](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
[Link]()
Out[17]: <[Link] at 0x7931c3562f50>
18
In [18]: # Using vmin, vmax and norm parameter
import [Link] as mcolors
fig = [Link](figsize=(3, 2), dpi=150)
N = 40
x = [Link](N)
y = [Link](N)
colors = [Link](N)
n = [Link](vmin=-2.,vmax=2.) # We have to use, mcolors to use, vmin and vm
[Link](x, y, c=colors, norm=n, cmap='viridis') # In cmap we have huge color comb
[Link]()
[Link]()
19
In [19]: # Using data parameter
fig = [Link](figsize=(3, 2), dpi=150)
df = [Link]({
'a': [Link](1000),
'b': [Link](1000),
'c': [Link](1000)
})
[Link]('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
[Link]()
Stem Plot
plt.fill_between(x, y1, y2)/ [Link](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 = [Link](figsize=(3, 2), dpi=150)
# Filled area between
sub = ["Machine Learning", "Maths", "Deep Learning", "NLP"]
std1 = [92, 88, 60, 72]
[Link](sub, std1)
plt.fill_between(sub, std1)
Out[34]: <[Link] at 0x7931c1718670>
The baseline parameter is used to denote the method used to calculate the baseline:
2. Statistical distributions
Histogram:
[Link](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:
[Link](X)
Violin Plot:
[Link](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
[Link](data)
Out[54]: {'bodies': [<[Link] at 0x7931c1625db0>,
<[Link] at 0x7931c0fa2710>,
<[Link] at 0x7931c0fa2a70>,
<[Link] at 0x7931c0fa2dd0>],
'cmaxes': <[Link] at 0x7931c1168220>,
'cmins': <[Link] at 0x7931c0fa3430>,
'cbars': <[Link] at 0x7931c0fa3820>}
Hist 2D:
plt.hist2D(x, y)
48
In [55]: # Create data
[Link](0)
x = [Link](0, 1, 1000)
y = [Link](0, 1, 1000)
# Create 2D histogram
plt.hist2d(x, y, bins=(50, 50), cmap=[Link])
[Link]()
Out[55]: <[Link] at 0x7931c102b460>
Hexbin:
[Link](x, y)
49
In [56]: import [Link] 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
[Link](x, y, gridsize=30, cmap='Greens')
# Add a colorbar for reference
[Link]()
# Show the plot
[Link]()
Pie Plot
In [57]: [Link]([1])
[Link]()
51
In [58]: # Number of memberss in household showing through pie chart and percentage
[Link](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
[Link](count, labels=label)
[Link]()
52
In [59]: # Using the parameters inside [Link]() graph
[Link](1, figsize=(6,6))
label=file.MALE_MEMBERS.value_counts().index
count=file.MALE_MEMBERS.value_counts().values
[Link]("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']
[Link](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)
[Link](loc = 'upper right')
[Link]()
53
In [60]: # Number of memberss in household showing through donout chart and percentage
# We can also create donout chart, through [Link]().add_artist
[Link](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
[Link](count, labels=label, radius = 1.2)
[Link]([1], colors = 'w', radius = 0.6)
[Link]()
54
In [61]: # Creating multiple pie graph in a chart
[Link](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']
[Link](male, labels=label, radius = 1.2)
[Link](female, labels=label, radius = 0.8, colors = co)
[Link]()
3. Gridded data
[Link](Z)
<class '[Link]'>
(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]
[Link](gray_robo)
[Link]()
[Link]['[Link]'] # Getting default image size
Out[63]: [6.4, 4.8]
57
In [64]: # Showing image in different colors
color_robo = [Link]('/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 = [Link](nrows = 2, ncols = 3, figsize = [Link](1/2)) # Figas
map = ['plasma', 'Wistia', 'gray', 'magma', 'jet', 'inferno']
for i, cmap in zip([Link], map):
[Link](robo_2D, cmap = cmap)
[Link](title = cmap)
[Link]('off')
[Link]()
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 [Link]).
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 [Link]() and [Link]() are almost same, there is no major differance.
Only, cntourf will help to fill the area.
66
In [75]: fig = [Link](figsize=(4, 2), dpi=150)
# Create a 2D array with random values
Z = [Link]((10,10))
# Display the array
[Link](Z)
Out[75]: <[Link] at 0x7931c08ae200>
Streamplot:
[Link](X, Y, U, V)
68
In [78]: fig = [Link](figsize=(4, 3), dpi=150)
# Create a grid of points
x = [Link](-2, 2, 100)
y = [Link](-2, 2, 100)
X, Y = [Link](x, y)
# Create a simple vector field: a vortex centered at the origin
U = -Y
V = X
# Create a stream plot
[Link](X, Y, U, V, density=2, linewidth=1, arrowsize=1, cmap='viridis')
Out[78]: <[Link] at 0x7931c040e530>
Scatter 3D Plot:
[Link](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 = [Link](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 = [Link]()
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 = [Link]()
# 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 = [Link](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 = [Link]()
ax = fig.add_subplot(111, projection='3d')
x = [Link](-5, 5, 100)
y = [Link](-5, 5, 100)
x, y = [Link](x, y) # ‘list’ object has no attribute ‘ndim’ typically occurs whe
# instead. The .ndim attribute is used to get the number of
z = [Link]([Link](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 = [Link]()
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 = [Link](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 = [Link]()
# 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 = [Link](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 = [Link]()
ax = fig.add_subplot(111, projection='3d')
x = [Link](-5, 5, 100)
y = [Link](-5, 5, 100)
x, y = [Link](x, y)
z = [Link]([Link](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 = [Link]()
ax_car = fig.add_subplot(111 , projection = '3d')
x = df_car[['Year']]
y = df_car[['Buyers']]
x, y = [Link](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
[Link](file_name)
82
In [92]: fig = [Link](figsize=(3,2), dpi=150)
# Can save 2d and 3d plot
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
[Link](name, marks)
[Link]("[Link]", # 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 = [Link](figsize=(3,2), dpi=150)
# Adding labels in plot
name = (1, 2, 3)
marks = [96, 80, 60]
[Link](name, labels = ['Subha', 'Subhajit Das', 'Subhajit'])
[Link](marks)
[Link](name, marks)
Out[93]: <BarContainer object of 3 artists>
84
In [94]: fig = [Link](figsize=(3,2), dpi=150)
# Specify limit in plot
name = (1, 2, 3)
marks = [96, 80, 60]
[Link](name, labels = ['Subha', 'Subhajit Das', 'Subhajit'])
[Link](marks)
[Link](0,2)
[Link](45,100)
[Link](name, marks, color = 'orange')
Out[94]: <BarContainer object of 3 artists>
Text in Matplotlib
85
In [95]: fig = [Link](figsize=(3, 2), dpi=150)
name = ('Subha', 'Subhajit Das', 'Subhajit')
marks = [96, 80, 60]
[Link]("Student Marks", fontsize = 12)
[Link]("Names", fontsize = 12)
[Link]("Marks", fontsize = 12)
[Link](0,88,"Calculas", # row position, column position, text
fontsize = 8,
style = 'italic',
bbox = {'facecolor' : 'green'})
[Link]("Deep Learning", xy=(1,76), # text, arrow position
xytext = (0.5, 60), # text position
arrowprops = dict(facecolor = 'black', shrink = 0.1)) # arrow color, arr
[Link](name, marks, label = 'Marks')
[Link](loc = 1,
facecolor = 'orange',
edgecolor = 'red',
framealpha = 0.8,
shadow = True)
Out[95]: <[Link] at 0x7931be390b80>
The 'use_line_collection' parameter in plt.stem() when set to True enhances performance by rendering stem lines as a collection rather than individually, which is computationally more efficient. Matplotlib 3.6 deprecated 'use_line_collection' as a positional parameter, recommending it be passed as a keyword argument due to planned removals in future releases .
The 'corner_mask' parameter in plt.contour() influences whether lines drawn ignore masked regions (when disabled) or interpolate excluding masked corners (when enabled), affecting the shape smoothness around corners. Enabling it may result in smoother and more continuous lines around masked data, improving plot aesthetics and accuracy .
Aspect ratio controls how an image's width and height relate when displayed, which can affect the perception of the image's geometry. Interpolation affects image quality by determining how pixel values are calculated in scaled versions, with options such as 'nearest', 'bilinear', or 'bicubic' altering the smoothness or sharpness of rendered images .
Step plots are beneficial when visualizing changes at discrete intervals with constant periods, as they clearly depict steps or transitions between levels. Real-world examples include stock price movements during trading sessions, where price remains constant between trades, or machinery cycling between states such as on-off in manufacturing processes .
The plt.stackplot() function offers baseline methods: 'zero' provides a simple addition of data from a constant base; 'sym' creates a symmetric baseline around zero; 'wiggle' minimizes the squared slope changes, creating a visually flowing plot; and 'weighted_wiggle', similar to 'wiggle', accounts for each layer's size, enhancing visual balance in stacked plots by spreading out layers uniformly .
The plt.stem() function in Matplotlib allows control over various parameters: 'locs' and 'heads' determine the x/y positions of the stem heads; 'linefmt' and 'markerfmt' define the color and style of the vertical lines and markers, respectively; 'basefmt' specifies the baseline format; 'bottom' sets the y-position of the baseline; 'use_line_collection' is a boolean indicating whether to create stem lines as a LineCollection; and 'orientation' decides if the stems are vertical or horizontal .
Contour plots (plt.contour()) illustrate the boundary lines at distinct levels, useful for showing data gradients, while filled contour plots (plt.contourf()) fill spaces between boundary lines with colors, which can emphasize area and sections between levels. Use plt.contourf() for visual emphasis on areas rather than boundaries .
The 'where' parameter in plt.fill_between() is a boolean array that specifies where to fill between two curves. It's useful for highlighting specific x-ranges where certain conditions are met, such as when data values fall within a particular range, or for visual emphasis in regions of interest on the plot .
plt.pcolormesh() allows the user to specify the grid's corner coordinates, making it useful for non-rectangular grids and irregular spacing, while plt.imshow() is simpler but constrained to uniform grids. plt.pcolormesh() can also efficiently handle large datasets due to its attention to pixel alignment (“snap” parameter) and provides more flexibility with parameters like 'edgecolors' and 'shading' .
Colormaps translate numerical data values into perceptually distinct colors, providing intuitive visual gaps and increments. They are essential for understanding gradients or concentrations in a plot, making data correlations more apparent. In plt.contour() or plt.pcolormesh(), altering colormaps can significantly aid interpretation of data patterns, such as temperature distributions or elevation maps .