MATPLOTLIB Mastery in 4 Hours
MATPLOTLIB Mastery in 4 Hours
Page 1 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Curated by
SAURABH G
Founder at DataNiti
6+ Years of Experience | Senior Data Engineer
Linkedin: www.linkedin.com/in/saurabhgghatnekar
BHAVESH ARORA
Senior Data Analyst at Delight Learning Services
M.Tech – IIT Jodhpur | 3+ Years of Experience
Linkedin: www.linkedin.com/in/bhavesh-arora-11b0a319b
Page 2 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Why Matplotlib?
1. Importing Matplotlib
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.show()
• plot(x, y): Draws a line connecting (x, y) points.
• show(): Renders the plot window.
3. Anatomy of a Figure
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
4. Save a Plot
plt.plot(x, y)
plt.savefig('line_plot.png')
plt.show()
Page 3 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Key Takeaways:
Q1: How does Matplotlib's object-oriented API (using Figure and Axes) differ from the
pyplot state-machine API?
A:
• The pyplot API (plt.plot()) is like a state machine: it keeps track of the current
figure and axes.
• The object-oriented API (fig, ax = plt.subplots()) gives explicit control over each
figure and axes, allowing multiple customizations, better for large/complex plots.
Q2: In a Matplotlib figure, how would you create two subplots and plot different datasets
without using plt.subplot()?
A:
Use fig, (ax1, ax2) = plt.subplots(1, 2) and then use ax1.plot(...), ax2.plot(...) separately.
This is more maintainable for multiple subplots.
Q3: If you call plt.plot() multiple times without calling plt.show(), what happens?
A:
All plots get layered on the same figure until show() is called. Each plot() adds another line
unless a new figure is created with plt.figure() or fig, ax = plt.subplots().
End of Day 1!
Page 4 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.plot(x, y, color='green')
plt.show()
• color='color_name' → Changes line color (e.g., 'red', 'blue', HEX codes like #FF5733).
• Common options:
o '-' → Solid
o '--' → Dashed
o '-.' → Dash-dot
o ':' → Dotted
3. Add Markers
plt.plot(x, y, marker='o')
plt.show()
Page 5 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
5. Short-Hand Notation
plt.plot(x, y, 'g--o')
plt.show()
• 'g' → Green
• '--' → Dashed Line
• 'o' → Circle Marker
Key Takeaways:
Q1: What is the precedence when you specify both shorthand and explicit arguments like
color, linestyle, and marker?
A:
• Explicit keyword arguments (like color='red', linestyle='--') override shorthand style
strings if conflicts arise.
Q2: How would you plot multiple lines with different styles efficiently inside a loop?
A:
• Maintain lists of colors, markers, linestyles, and loop through them when plotting.
Example:
Q3: How would you customize a plot when color-blind users must be able to distinguish the
lines?
Page 6 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
A:
• Use different markers and different linestyles, not just colors.
• Prefer color palettes like Color Universal Design (CUD) or use Matplotlib’s color-
blind friendly colormaps like 'tab10', 'Set2', etc.
End of Day 2!
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.plot(x, y)
plt.title('Simple Line Plot')
plt.xlabel('X-axis Values')
plt.ylabel('Y-axis Values')
plt.show()
plt.plot(x, y)
plt.title('Customized Plot', fontsize=16, color='blue')
plt.xlabel('Input', fontsize=12)
plt.ylabel('Output', fontsize=12)
plt.show()
Page 7 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
3. Adding a Legend
y2 = [3, 6, 9, 12]
plt.plot(x, y, label='2x')
plt.plot(x, y2, label='3x')
plt.title('Multiple Lines')
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.legend()
plt.show()
Key Takeaways:
Page 8 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Q1: How does plt.legend() decide the placement when loc='best' is used, and what can go
wrong with it?
A:
• 'best' automatically finds an area with the least data overlap.
• However, if the plot is densely packed, even 'best' can overlap with critical parts of
the graph, requiring manual adjustment.
Q2: How would you create a custom legend without associating it directly with plotted
lines?
A:
• Use plt.legend(handles=[custom_lines], labels=['label1', 'label2']) with custom Line2D
objects from matplotlib.lines. Example:
Q3: Why should you avoid hardcoding legend locations in dynamic plots, and what’s a
better strategy?
A:
• Hardcoding (loc='upper right') may cause overlap when plot contents change.
• A better strategy is dynamic calculation using bounding boxes (bbox_to_anchor) or
designing plots with margins to accommodate legends.
End of Day 3!
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
Page 9 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
plt.plot(x, y)
plt.title('Saving Example')
plt.savefig('myplot.png') # Default DPI = 100
plt.plot(x, y)
plt.title('High Quality Transparent')
plt.savefig('clean_plot.png', dpi=300, transparent=True)
plt.plot(x, y)
plt.title('Tight Layout')
plt.tight_layout()
plt.savefig('tight_plot.png', bbox_inches='tight')
Page 10 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Key Takeaways:
Q1: You notice labels are cut off in your saved image. How would you fix this using
matplotlib?
Example:
plt.tight_layout()
plt.savefig('plot.png', bbox_inches='tight')
Q2: How does changing DPI affect file size and resolution in saved figures?
A:
• DPI controls how many pixels are rendered per inch.
• Higher DPI = larger file size and sharper image.
• Critical for print vs. screen distinction. E.g., 72–100 for web, 300+ for publications.
Q3: What is the difference between figsize and dpi, and how do they combine to define
image resolution?
A:
• figsize defines size in inches, dpi defines pixels per inch.
• Total resolution = figsize[0] * dpi (width in px) × figsize[1] * dpi (height in px).
• For example: figsize=(8, 4), dpi=100 → image is 800×400 px.
Q4: Why might you choose transparent=True when saving a plot, and what are the risks?
A:
• Use transparent=True when overlaying plots on non-white backgrounds (e.g.,
websites or slides).
• Risk: If plot elements (e.g., text) are also light-colored, visibility might be reduced
or lost.
Page 11 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 3, 5, 7]
plt.subplot(1, 2, 2)
plt.plot(x, y2)
plt.title('Prime')
plt.tight_layout()
plt.show()
• 1 row, 2 columns
• Index starts at 1, not 0
• Use tight_layout() to avoid overlap
axs[1].plot(x, y2)
axs[1].set_title('Prime')
plt.tight_layout()
plt.show()
Page 12 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
for i in range(3):
axs[i].plot(y_data[i])
axs[i].set_title(titles[i])
plt.tight_layout()
plt.show()
4. Sharing Axis
Key Takeaways:
Page 13 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Q2: You have a 2×2 subplot grid, but only want to display 3 plots. How do you leave one
blank without breaking the layout?
A:
• Skip plotting in one of the axes or turn it off:
axs[1, 1].axis('off')
Q4: How can you dynamically plot an unknown number of charts using subplots?
A:
• Use plt.subplots(n) where n is the number of charts.
• Loop through the returned axs and plot:
End of Day 5!
Page 14 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.plot(x, y)
plt.title('Custom Axis Labels')
plt.xlabel('Time (s)')
plt.ylabel('Distance (m)')
plt.show()
plt.plot(x, y)
plt.title('Custom Ticks')
plt.xticks([1, 2, 3, 4], ['1s', '2s', '3s', '4s']) # Custom x-tick labels
plt.yticks([2, 4, 6, 8], ['2 meters', '4 meters', '6 meters', '8 meters']) # Custom y-tick labels
plt.show()
plt.plot(labels, values)
plt.xticks(rotation=45) # Rotates x-axis labels by 45 degrees
plt.show()
• Use rotation for angled labels, especially useful when the labels overlap
plt.plot(x, y)
plt.title('Custom Axis Limits')
plt.xlim(0, 5) # Set x-axis from 0 to 5
Page 15 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
5. Logarithmic Scales
plt.plot(x, y)
plt.title('Logarithmic Scale')
plt.xscale('log') # Set x-axis to logarithmic scale
plt.yscale('log') # Set y-axis to logarithmic scale
plt.show()
ax1.plot(x, y, 'g-')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Distance (m)', color='g')
plt.show()
Key Takeaways:
Page 16 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Q1: How would you adjust the axis limits if you have an outlier in your dataset that makes
the rest of the data hard to visualize?
A:
• Use set_xlim() and set_ylim() to zoom in on the relevant portion of the data and
exclude outliers.
• Alternatively, you could use a log scale to compress the scale and show the data
more effectively.
Q2: What is the advantage of using a logarithmic scale in plots, and when should it be
used?
A:
• Logarithmic scales are used when data spans several orders of magnitude. They help
visualize data that has exponential growth, like population growth or financial data.
• Example: Plotting the population growth of countries or stock prices over time.
Q3: You’re plotting a dataset with categories on the x-axis and values on the y-axis.
However, the x-axis labels are overlapping. How would you solve this issue?
A:
• Use plt.xticks(rotation=45) to rotate the labels for better visibility.
• Alternatively, reduce the number of ticks or adjust their positions using xticks().
Q4: You need to create two plots in one figure: one showing distance over time and
another showing speed over time. The y-axes are in different units. How would you do this
in Matplotlib?
A:
• Use twinx() to create two y-axes: one on the left for distance, another on the right
for speed.
Example:
ax1 = plt.gca() # Get current axes
ax1.plot(x, distance_data)
ax2 = ax1.twinx()
ax2.plot(x, speed_data)
End of Day 6!
Page 17 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.plot(x, y)
plt.title('Linear Growth Over Time')
plt.xlabel('Time (s)')
plt.ylabel('Distance (m)')
plt.show()
• Use plt.title() to add a title to your plot, making it clear what the graph represents.
• You can also customize the font size, family, and style using parameters like
fontsize, fontweight, and family.
x = [1, 2, 3, 4]
y1 = [2, 4, 6, 8]
y2 = [1, 3, 5, 7]
plt.xlabel('Time (s)')
plt.ylabel('Value')
plt.legend(title='Measurements')
plt.show()
Page 18 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
plt.xlabel('Time (s)')
plt.ylabel('Value')
plt.title('Speed vs Distance')
plt.xlabel('Time (s)')
plt.ylabel('Value')
plt.title('Speed vs Distance')
• You can modify the gridline style using linestyle, linewidth, and color for a more
customized look.
plt.xlabel('Time (s)')
plt.ylabel('Value')
plt.title('Speed vs Distance')
• loc='best': Automatically places the legend in the optimal position to avoid overlap.
• tight_layout(): Adjusts the spacing of the plot to ensure no labels or titles are
clipped.
Key Takeaways:
Q1: How would you add a title to a plot in Matplotlib, and why is it important?
A:
• You can add a title using plt.title('Your Title'). A title helps provide context for the
plot, making it clear what the plot represents (e.g., "Sales Growth Over Time").
Q2: You have multiple plots, and the axis labels or legends are being cut off. How would
you fix this?
A:
• Use plt.tight_layout() to automatically adjust the spacing between elements in the
plot and prevent clipping of labels or titles.
• Alternatively, you can manually adjust the margins using plt.subplots_adjust().
Q3: You’re plotting two series, one for distance and one for speed, but the lines overlap in
the legend. How would you fix this?
A:
• You can modify the legend’s position using the loc parameter, e.g.,
plt.legend(loc='upper left') to move the legend to a less crowded area.
• Alternatively, use plt.legend(title='Measurements') to add a title to the legend for
clarity.
Q4: In what scenarios would you use plt.grid(True) in a plot, and how can you customize
the gridlines’ appearance?
A:
• plt.grid(True) is useful when you need to make the values in your plot easier to read
by providing horizontal and vertical lines.
• You can customize the gridlines by adjusting linestyle, linewidth, and color
parameters, e.g., plt.grid(True, linestyle='--', color='gray').
End of Day 7!
Page 20 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
• Colors: Differentiate data series and add meaning (e.g., red for negative, green for
positive).
• Styles: Customize the line, marker, and other visual elements to match the
presentation style or make specific data stand out.
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
• You can specify colors using named colors (e.g., 'red', 'green'), RGB tuples (e.g.,
(0.1, 0.2, 0.5)), or hexadecimal color codes (e.g., '#FF5733').
• Hexadecimal codes allow for precise control over the color (e.g., '#FF5733' for a
specific shade of red-orange).
Page 21 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
y2 = [1, 2, 3, 4]
plt.plot(x, y, color='blue', linestyle='-', marker='o', label='Line 1')
plt.plot(x, y2, color='red', linestyle='--', marker='s', label='Line 2')
• You can plot multiple lines with different styles and use plt.legend() to label each
line.
fig, ax = plt.subplots()
ax.plot(x, y, color='blue')
fig.patch.set_facecolor('#f2f2f2') # Set background color of the entire figure
import numpy as np
Key Takeaways:
• Colors: Use named colors, RGB tuples, or hexadecimal color codes to customize your
plot.
• Line Style and Markers: Change the appearance of your plot using linestyle and
marker.
Page 22 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
• Colormaps: For continuous data, use colormaps like viridis to represent values
visually.
• Background Color: Customize the plot background color to match your desired style.
Q1: How would you change the color of a line in Matplotlib? What are some ways to specify
the color?
A:
• You can specify the color using the color parameter in plt.plot(). Colors can be
specified as named colors (e.g., 'blue'), RGB tuples (e.g., (0.1, 0.2, 0.5)), or
hexadecimal color codes (e.g., '#FF5733').
Q2: How would you make the plot background color different from the default white?
A:
• You can change the figure background color using fig.patch.set_facecolor(). For
example, fig.patch.set_facecolor('#f2f2f2') changes the background color to a light
gray.
Q3: You have two lines to plot on the same graph, and you want one line to be dashed and
the other solid. How would you accomplish this?
A:
• You can use the linestyle parameter in plt.plot(). For example, use linestyle='-' for
the solid line and linestyle='--' for the dashed line.
Q4: What is the purpose of cmap in Matplotlib, and how do you use it in scatter plots?
A:
• cmap is used to apply a colormap to continuous data, allowing you to visually
differentiate values. You can use it with scatter plots to color points based on their
value, e.g., plt.scatter(x, y, c=z, cmap='viridis') where z is the data to be mapped to
colors.
Q5: How would you display a color legend on a scatter plot when using a colormap?
A:
• You can use plt.colorbar() to display the color legend or scale for the colormap in a
scatter plot.
End of Day 8!
Page 23 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
plt.show()
• plt.subplot(nrows, ncols, index) divides the figure into nrows rows and ncols
columns, and index specifies the subplot position (1-based index).
The plt.subplots() method is a more flexible way to create subplots, returning a figure and
an array of axes.
• This approach returns fig (the figure object) and axs (an array of axes), which you
can use to plot on specific subplots.
Page 24 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
plt.tight_layout()
plt.show()
• You can customize each subplot individually, changing titles, labels, etc.
• sharex=True and sharey=True allow you to link the x-axis or y-axis between subplots,
making comparisons easier.
plt.tight_layout()
plt.show()
Page 25 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Key Takeaways:
• Use plt.subplot() for basic subplot creation with a single function call.
• plt.subplots() returns a figure and axes, allowing for more customization.
• You can share axes between subplots to make comparisons easier.
• Use figsize to control the size of the overall figure.
Q2: How would you make two plots in a grid with shared x-axis?
A:
• Use plt.subplots() with sharex=True. For example: fig, axs = plt.subplots(2, 1,
sharex=True) will create two subplots stacked vertically with a shared x-axis.
Q4: How would you adjust the size of subplots to fit more details?
A:
• You can use the figsize parameter in plt.subplots(), e.g., fig, axs = plt.subplots(2, 2,
figsize=(10, 6)), to control the figure size for better visualization.
Q5: How can you share both x and y axes between multiple subplots?
A:
• When creating subplots with plt.subplots(), you can use sharex=True and
sharey=True to share both axes between subplots. This is useful for comparing
trends across multiple subplots with the same axis scales.
End of Day 9!
Page 26 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
To plot 3D data, you need to import the Axes3D module and create a 3D axes object.
# Create data
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))
# Plot 3D surface
ax.plot_surface(x, y, z, cmap='viridis')
plt.show()
2. Adding Annotations
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y, 'bo-')
Page 27 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
# Add annotation
plt.annotate('Max Point', xy=(3, 25), xytext=(2, 28),
arrowprops=dict(facecolor='black', arrowstyle='->'),
fontsize=12)
plt.show()
• annotate() adds text annotations. You can also add an arrow with arrowprops to
point to a specific location.
3. Customizing Legends
Legends are crucial for understanding what each plot represents. Customizing legends can
make them more informative and visually appealing.
# Create data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Customize legend
plt.legend(loc='upper right', fontsize=12, title='Trigonometric Functions')
plt.show()
• plt.legend() adds the legend, where loc specifies the location and title adds a title
to the legend.
• You can also change the font size and style with fontsize.
You can modify the tick marks and labels on both x and y axes for better clarity.
plt.plot(x, y)
plt.show()
• xticks() and yticks() allow you to change the tick positions and labels.
Page 28 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
You can plot multiple datasets on the same figure with different styles, colors, and
markers.
plt.legend()
plt.show()
• Customize line style, color, and marker type using linestyle, color, and marker
parameters.
Key Takeaways:
Q2: What’s the purpose of annotations, and how can you add an arrow to highlight a point?
A:
• Annotations are used to add textual information to specific points in the plot,
improving its clarity.
• Use plt.annotate() with the arrowprops parameter to add arrows pointing to specific
data points.
Page 29 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Q4: How do you adjust the ticks and labels on both x and y axes in Matplotlib?
A:
• Use plt.xticks() and plt.yticks() to modify tick positions and labels. You can specify
both the tick positions and their corresponding labels.
Q5: Can you explain how to plot multiple datasets with different line styles and markers?
A:
• Use the plt.plot() function for each dataset, and customize the line style with
linestyle, the color with color, and markers with marker. You can then add a legend
to differentiate between the datasets.
• Trend Analysis: Time series allows you to observe data trends over time (e.g., stock
prices, temperature changes).
• Data Intervals: You can easily plot data points that correspond to specific time
intervals.
• Annotations and Markers: Highlight key events or changes over time.
For time series data, the x-axis typically represents time, while the y-axis represents the
value of the variable you are tracking.
# Create a DataFrame
df = pd.DataFrame({'Date': date_range, 'Value': data})
You can format the date axis using mdates.DateFormatter for better readability.
plt.show()
• mdates.DateFormatter() allows you to specify a custom format for the dates (e.g.,
year-month-day).
• You can modify the format to display more or less information, such as just the year
('%Y').
Often, time series data is in higher frequency (e.g., minute-wise) and you might want to
resample it to a lower frequency (e.g., daily averages).
• resample() is used to change the frequency of the time series. 'D' stands for daily
frequency.
• The mean is calculated for each day in the resampled data.
Sometimes, you may want to highlight specific periods in your time series plot (e.g.,
anomalies or special events).
# Add legend
plt.legend()
Key Takeaways:
• Use pd.date_range() to create time series data, and plot it using plt.plot().
• Customize the x-axis for date formatting using mdates.DateFormatter().
• Resampling allows you to change the frequency of your time series data (e.g., from
hourly to daily).
• You can highlight specific date ranges with axvspan() to focus on important periods.
• Multiple time series can be compared in the same plot, helping visualize
relationships between different datasets.
Q1: How do you format the date on the x-axis in a Matplotlib plot?
A:
• Use matplotlib.dates.DateFormatter to format the date axis, specifying the desired
format (e.g., '%Y-%m-%d').
Q2: How would you handle a high-frequency time series and resample it to a lower
frequency?
A:
• Use df.resample('D', on='Date').mean() to resample the time series to a daily
frequency, calculating the mean for each day.
Q3: How can you highlight a specific date range in a time series plot?
A:
• Use plt.axvspan(start_date, end_date, color='color', alpha=0.3) to highlight a date
range by adding a shaded region.
Q4: Can you explain how to plot multiple time series on the same plot?
A:
• You can plot multiple time series by calling plt.plot() for each series and use
plt.legend() to distinguish between them.
Q5: What is the purpose of resampling in time series analysis, and how is it done in Pandas?
A:
• Resampling changes the frequency of time series data (e.g., from hourly to daily).
It’s done using the resample() function, which allows you to aggregate or interpolate
the data.
Page 33 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
• Compact Visualization: Display multiple charts in a single figure to save space and
make comparisons.
• Ease of Comparison: Place related plots next to each other for side-by-side
comparison.
• Organized Presentation: Make your visualizations cleaner and more organized.
The plt.subplot() function is used to create subplots. It takes 3 arguments: the number of
rows, the number of columns, and the index of the subplot.
• plt.subplot(1, 2, 1) creates a subplot grid of 1 row and 2 columns, and the 1 refers
to the position of the first plot.
• plt.subplot(1, 2, 2) creates the second plot in the grid.
• fig, axes = plt.subplots(2, 2) creates a 2x2 grid of subplots, where axes is a 2D array
of subplot axes.
• Each subplot is accessed via the axes array (e.g., axes[0, 0] refers to the first
subplot).
Sometimes, you might want to share the x-axis or y-axis across multiple subplots for easier
comparison. This can be done using the sharex and sharey parameters in plt.subplots().
plt.tight_layout()
plt.show()
• sharex=True ensures all subplots share the same x-axis, making it easier to compare
data across subplots.
• Similarly, sharey=True can be used to share the y-axis.
Page 35 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
gridspec gives you more control over subplot positioning and sizes.
plt.tight_layout()
plt.show()
• gridspec.GridSpec() creates a flexible grid layout. You can span subplots across
multiple rows or columns using slicing, such as gs[1, :] (spanning the second row).
You can set a custom size for the entire figure using the figsize argument in plt.subplots()
or fig.figure(figsize=(width, height)).
plt.tight_layout()
plt.show()
Key Takeaways:
• plt.subplot() is used for basic subplot layouts with specific grid sizes.
• plt.subplots() is more flexible and returns both a figure and axes objects for easy
subplot manipulation.
• You can share axes between subplots to align data for easier comparison.
Page 36 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Q1: How does plt.subplots() differ from plt.subplot() in terms of functionality and
flexibility?
A:
• plt.subplots() is more flexible, returning both the figure and axes objects, allowing
easier customization of multiple subplots. It also supports shared axes.
• plt.subplot() creates individual subplots but requires manual handling of subplot
positions, and it’s less flexible for complex layouts.
Q3: How would you use gridspec to customize the layout of subplots in a figure?
A:
• gridspec.GridSpec() allows creating custom grid layouts where subplots can span
multiple rows or columns. You can create non-uniform layouts, such as having one
subplot span two columns or a row.
Q4: What would you do if you need a larger space for one of your subplots in a multi-plot
layout?
A:
• You can adjust the size of subplots using gridspec or by manually setting the position
of that subplot using plt.subplots_adjust() or by adjusting figsize.
Q5: How do you adjust the spacing between subplots to avoid overlapping plots or labels?
A:
• Use plt.tight_layout() to automatically adjust spacing between subplots, ensuring
that they do not overlap. You can also manually adjust spacing using
plt.subplots_adjust().
Page 37 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
• Visual Appeal: Make your plots more aesthetically pleasing for better
communication.
• Consistency: Use a consistent style across all visualizations in a project or report.
• Highlight Key Insights: Custom styles can help emphasize specific parts of the plot,
such as trends or outliers.
Matplotlib comes with a variety of pre-defined styles that can be applied to your plots
using plt.style.use().
print(plt.style.available)
You can modify individual elements of your plot, such as the color, line style, marker style,
and more, by using the corresponding parameters.
You can modify axes limits, labels, and gridlines to improve the readability of the plot.
# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
You can customize font properties such as size, family, and weight for titles, labels, and
ticks.
# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
You can create your own custom styles by creating a .mplstyle file, which contains settings
for various elements of the plot.
axes.titlesize: 18
axes.labelsize: 14
axes.labelweight: bold
axes.grid: True
grid.linestyle: '-'
grid.color: blue
lines.linewidth: 2
lines.color: green
After customizing your plot, you can save it to a file with a specific format and resolution
using plt.savefig().
# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
Page 40 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
# Save the plot as a PNG image with 300 dpi
plt.savefig('custom_plot.png', dpi=300)
plt.show()
Key Takeaways:
• Use built-in styles with plt.style.use() to quickly change the look of your plots.
• Customize individual plot elements like lines, markers, axes, and gridlines for more
control over the visual appearance.
• Create custom styles by defining your own .mplstyle file for consistent formatting
across plots.
• Customize font properties to adjust text size, family, and weight.
• Save plots with plt.savefig() to export them in high resolution and various formats.
Q1: How can you create and apply your own custom style in Matplotlib?
A:
• Create a .mplstyle file that contains custom settings for plot elements like axes,
gridlines, lines, and fonts. Use plt.style.use('my_style.mplstyle') to apply the style to
a plot.
Q2: When would you use plt.tight_layout() in relation to customizing plot styles, and why?
A:
• plt.tight_layout() is used to adjust the spacing between subplots or plot elements
(like titles, labels, and ticks). It ensures that nothing overlaps and the plot looks
neat, especially after customizing the layout and adding multiple elements.
Q3: How would you change the font style of axis labels and title in a Matplotlib plot?
A:
• Use fontsize, family, and fontweight parameters in functions like plt.title(),
plt.xlabel(), and plt.ylabel() to customize the font size, family, and weight of titles
and labels.
Q4: What is the purpose of sharex and sharey when creating multiple subplots, and how
would you use them?
A:
• sharex=True and sharey=True are used to ensure that all subplots share the same
x-axis or y-axis, respectively. This is particularly useful when comparing data across
subplots as it avoids inconsistent axis scaling.
Page 41 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Q5: How would you save a plot with a transparent background and high resolution?
A:
• Use plt.savefig('filename.png', dpi=300, transparent=True) to save the plot with
300 dpi resolution and a transparent background.
1. Creating Subplots
Matplotlib allows you to create multiple plots within a single figure using plt.subplots().
This is especially useful for comparing multiple datasets side by side.
Page 42 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
2. Polar Plots
Polar plots are useful for data that has a cyclic or angular nature, such as angles,
directions, and periodic data.
plt.title('Polar Plot')
plt.show()
3. 3D Plots
Matplotlib allows you to create 3D plots for visualizing data in three dimensions. You can
use this for 3D scatter plots, surface plots, and more.
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Scatter plot
ax.scatter(x, y, z)
Page 43 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
4. Annotating Plots
You can add annotations to highlight specific points or areas of interest in your plots.
# Plot data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.title('Annotated Plot')
plt.show()
• plt.annotate(): Adds an annotation to a plot. You can specify the text, position, and
an arrow to point to a specific data point.
Matplotlib can be made interactive using widgets in Jupyter notebooks. This allows users to
change plot parameters interactively, such as adjusting axis limits or plot types.
6. Heatmaps
Heatmaps are a great way to visualize matrix-like data or 2D datasets, showing how values
vary across the matrix with colors.
# Create a heatmap
plt.imshow(data, cmap='viridis', interpolation='nearest')
plt.colorbar() # Show color scale
plt.title('Heatmap')
plt.show()
Key Takeaways:
Page 45 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Q2: Can you explain how plt.subplots() works, and what parameters are used to control
the layout of subplots?
A:
• plt.subplots() creates a figure and an array of subplots. You can control the layout
using parameters like nrows, ncols, and sharex/sharey to share axes between
subplots.
Q4: How would you make your plot interactive in Jupyter Notebooks?
A:
• Use ipywidgets to create interactive widgets (like sliders, buttons) that allow you to
dynamically update the plot based on user input.
Q5: What are the common color maps in heatmaps, and how would you choose one?
A:
• Common color maps include viridis, plasma, inferno, coolwarm, etc. The choice
depends on the nature of the data, e.g., coolwarm for data with both negative and
positive values, and viridis for visually pleasant continuous data.
1. Customizing Legends
Legends help explain what each plot element (line, scatter point, bar, etc.) represents.
Matplotlib allows you to customize the position, title, fonts, and more for legends.
Basic Legend:
Page 46 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [1, 2, 3, 4]
# Add legend
plt.legend()
plt.show()
# Customizing legend
plt.legend(loc='upper left', fontsize='large', title='Function Types')
plt.show()
• loc: Defines the position of the legend (e.g., 'upper left', 'lower right').
• fontsize: Customizes the font size.
• title: Adds a title to the legend.
If you have multiple elements in a plot, you can create more sophisticated legends with
groupings or selective entries.
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [1, 2, 3, 4]
y3 = [1, 3, 6, 10]
plt.show()
Page 47 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
• handles: Manually specify which plot elements should appear in the legend.
3. Customizing Annotations
Annotations can be used to add text or highlight specific points on the plot, which can help
emphasize key insights.
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)
# Annotating a point
plt.annotate('Highest point', xy=(4, 16), xytext=(3, 15),
arrowprops=dict(facecolor='red', arrowstyle='->'))
plt.show()
You can also annotate multiple points or add text in different positions to provide further
context.
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)
plt.show()
Page 48 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
• You can add multiple annotations with different xy and xytext positions.
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)
plt.show()
• r'$y = x^2$': The r before the string allows you to use raw string literals, and the
LaTeX expression is placed between dollar signs ($).
Matplotlib provides various options for controlling text placement on the plot.
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)
plt.show()
Page 49 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Key Takeaways:
Q1: How can you place multiple legends in a plot, each referring to different parts of the
plot?
A:
• You can use plt.legend() with the handles parameter, which allows you to select
specific lines or elements to include in the legend. Alternatively, you can create
multiple legends using plt.legend() for different regions of the plot.
Q2: What is the difference between using annotate() and text() for adding labels in
Matplotlib?
A:
• annotate() is used when you want to point to a specific data point with an arrow or
other visual cues, whereas text() is used for placing arbitrary text at a specific
location on the plot without pointing to any data point.
Q4: What is the importance of customizing legend positions, and how can you do it?
A:
• Customizing the position of legends ensures they do not overlap with the data. Use
the loc parameter in plt.legend() to control the legend’s position, e.g., 'upper left',
'center right'.
Q5: How do you highlight a point in your plot using annotation, and what parameters do
you need to control for customizing the arrow?
Page 50 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
A:
• Use plt.annotate() with the xy parameter for the point, xytext for the text position,
and arrowprops to customize the arrow’s appearance (e.g., color, style, width).
• Stacked bar charts are ideal when you want to display the composition of different
categories and show how subgroups contribute to a total.
• They are useful for comparing parts of a whole across different categories.
To create stacked bar charts in Matplotlib, you can use the stacked=True parameter in the
bar() function.
# Data
categories = ['A', 'B', 'C']
group1 = [3, 4, 2]
group2 = [1, 2, 3]
plt.show()
In this example, Group 1 is plotted first, and Group 2 is stacked on top of it using the
bottom parameter.
Page 51 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
You can further customize stacked bar charts by adjusting the colors and labels.
Example: Custom Stacked Bar Chart
plt.show()
Key Takeaways:
• Stacked Bar Charts are useful for comparing the contribution of different subgroups
to a total.
• Use bottom parameter to stack the bars on top of each other.
• Customize the chart with colors and labels for better readability.
Q1: When would you choose a stacked bar chart over a regular bar chart?
A:
• Use stacked bar charts when you need to show the total value along with the
composition of different categories. Regular bar charts are better when you want to
compare absolute values between categories.
Q2: How can you handle negative values in a stacked bar chart?
A:
• You can use the bottom parameter to adjust the positioning of negative bars,
ensuring they are stacked below the x-axis.
• Multiple subplots allow you to visualize different aspects of your data in one figure.
• Subplots are great when comparing multiple plots side by side or showing different
views of the same data.
ax[0].set_title('Line Plot')
ax[1].set_title('Bar Plot')
plt.show()
This creates a figure with two subplots arranged in a single row (1x2 grid).
fig, ax = plt.subplots(1, 2)
ax[0].plot([1, 2, 3], [1, 4, 9])
ax[1].bar(['A', 'B', 'C'], [3, 4, 5])
plt.show()
Key Takeaways:
Page 53 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
• Scatter plots are ideal for visualizing the relationship between two continuous
variables.
• They help detect patterns, trends, and outliers.
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.scatter(x, y)
plt.title('Basic Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Key Takeaways:
• Scatter plots are great for visualizing the correlation between two continuous
variables.
• You can customize the markers, size, and colors for better data presentation.
Page 54 of 57
MATPLOTLIB in 5 Hours Bhavesh Arora Learn Complete MATPLOTLIB Free
Q1: How would you visualize the relationship between three continuous variables?
A:
• Use a 3D scatter plot (Axes3D), where each axis represents a different variable.
• Pie charts are ideal for visualizing parts of a whole in categorical data.
• They show the relative proportion of each category as a slice of the pie.
You can adjust the colors, explode slices, and start the angle of the chart.
Key Takeaways:
• Pie charts are best for showing the proportional distribution of categories.
• Customize slice colors, labels, and the angle of the chart to improve visualization.
Q2: How can you handle the situation where one category has a very small percentage?
A:
• Consider using a bar chart instead or combine small categories into an "Other"
category.
• Line plots are excellent for visualizing trends over time or continuous data.
• They are simple and effective for showing the relationship between two variables.
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.title('Basic Line Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Key Takeaways:
Q1: When should you use a line plot instead of a bar chart?
A:
• Line plots are for continuous data (e.g., time-series), while bar charts are used for
categorical data comparison.
Q2: How can you display multiple line plots in one graph?
A:
• Simply call plot() multiple times for each dataset.
Page 57 of 57