Okay, let's put the concepts from this chapter into practice. You've learned how to add annotations, manage legends, adjust layouts, apply themes, and save your work. Now, you'll apply these techniques to refine some basic plots, making them clearer, more informative, and ready for sharing.
We'll work through enhancing a few common plot types. Remember to have your plotting libraries imported:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
# Sample data for practice
x_line = np.linspace(0, 10, 50)
y1_line = np.sin(x_line)
y2_line = np.cos(x_line)
categories = ['Group A', 'Group B', 'Group C', 'Group D']
values = [15, 24, 19, 29]
x_scatter = np.random.rand(50) * 10
y_scatter = x_scatter + np.random.randn(50) * 2
highlight_x = x_scatter[10] # Pick a point to highlight
highlight_y = y_scatter[10]
# Set a default Seaborn style for nicer aesthetics
sns.set_style("whitegrid")
Let's start with a simple line plot showing two lines. The default plot lacks context.
Initial Plot:
plt.figure(figsize=(8, 4)) # Start with a figure size
plt.plot(x_line, y1_line)
plt.plot(x_line, y2_line)
plt.show()
Tasks:
loc
values ('upper right', 'lower left', etc.) to find a good position.Refined Plot Code:
# 1. Create figure and axes
plt.figure(figsize=(8, 5)) # Adjusted size slightly
# 2. Plot data with customizations
plt.plot(x_line, y1_line, color='#1f77b4', linestyle='-', label='sin(x)') # Blue solid line
plt.plot(x_line, y2_line, color='#ff7f0e', linestyle='--', label='cos(x)') # Orange dashed line
# 3. Add title and labels
plt.title('Sine and Cosine Functions')
plt.xlabel('X Value')
plt.ylabel('Y Value')
# 4. Set axis limits
plt.ylim(-1.5, 1.5)
# 5. Add legend
plt.legend(loc='lower left') # Place legend in lower left
# 6. Show plot
plt.show()
Compare the refined plot to the initial one. The added elements make it much easier to understand what the visualization represents.
Now let's work with a scatter plot. We'll add an annotation to point out a specific data point.
Initial Plot:
plt.figure(figsize=(7, 5))
plt.scatter(x_scatter, y_scatter, alpha=0.7) # Use alpha for transparency
plt.title('Basic Scatter Plot')
plt.xlabel('X Variable')
plt.ylabel('Y Variable')
plt.show()
Tasks:
sns.set_style("darkgrid")
or sns.set_theme(style="ticks")
before creating the plot to see the difference.plt.annotate()
to add text pointing to the specific highlight_x
, highlight_y
point we defined earlier. Make the annotation informative.plt.tight_layout()
at the end (before plt.show()
) to automatically adjust spacing.Refined Plot Code:
# 1. Apply a different style (optional - try uncommenting)
# sns.set_theme(style="ticks")
plt.figure(figsize=(7, 5))
plt.scatter(x_scatter, y_scatter, alpha=0.7, color='#20c997') # Teal points
# 2. Add title and labels
plt.title('Scatter Plot with Annotation')
plt.xlabel('X Variable')
plt.ylabel('Y Variable')
# 3. Annotate the specific point
plt.annotate('Interesting Point', # Text to display
xy=(highlight_x, highlight_y), # Point to annotate (arrow tip)
xytext=(highlight_x + 1, highlight_y + 3), # Text position
arrowprops=dict(facecolor='#495057', shrink=0.05, width=1, headwidth=8)) # Arrow style
# 4. Adjust layout
plt.tight_layout() # Often useful for preventing overlaps
# 5. Show plot
plt.show()
# Optional: Reset style if you changed it
sns.set_style("whitegrid") # Set back to default for next exercise
Annotations help guide the viewer's attention to significant features within the data. plt.tight_layout()
is a convenient function for basic layout adjustments.
Bar charts often benefit from clear labels and appropriate colors.
Initial Plot (using Matplotlib):
plt.figure(figsize=(7, 4))
plt.bar(categories, values)
plt.title('Category Values')
plt.ylabel('Count')
plt.show()
Tasks:
barplot
or assign colors manually in Matplotlib. Let's try using Seaborn's barplot
for simplicity here.plt.xticks(rotation=45)
.Refined Plot Code (using Seaborn):
plt.figure(figsize=(8, 5))
# 1. Create barplot with a palette
# Seaborn's barplot uses the categories for x and values for y
sns.barplot(x=categories, y=values, palette='viridis')
# 2. Add title and labels (Seaborn sets some automatically, but we can customize)
plt.title('Values per Category')
plt.xlabel('Category Group')
plt.ylabel('Measured Value')
# 3. Add value labels (requires iterating through the bars created by Seaborn)
# Get the current Axes object
ax = plt.gca()
# Iterate through the patches (bars) in the Axes
for bar in ax.patches:
ax.text(bar.get_x() + bar.get_width() / 2., # X position (center of bar)
bar.get_height(), # Y position (top of bar)
f'{bar.get_height():.0f}', # Text (value, formatted)
ha='center', # Horizontal alignment
va='bottom') # Vertical alignment
# 4. Rotate x-axis labels (optional, uncomment to see effect)
# plt.xticks(rotation=45, ha='right')
# 5. Adjust layout
plt.tight_layout()
# 6. Show plot
plt.show()
Adding value labels and using distinct colors can significantly improve the readability and professional appearance of bar charts.
Finally, let's save one of the plots you refined. Saving allows you to use your visualization in reports, presentations, or on the web.
Task:
Save the refined Sine and Cosine line plot (from Practice 1) into three different formats: PNG, PDF, and SVG. Pay attention to the filename extensions.
Saving Code:
# Regenerate the Sine/Cosine plot first (copy code from Practice 1 refinement)
plt.figure(figsize=(8, 5))
plt.plot(x_line, y1_line, color='#1f77b4', linestyle='-', label='sin(x)')
plt.plot(x_line, y2_line, color='#ff7f0e', linestyle='--', label='cos(x)')
plt.title('Sine and Cosine Functions')
plt.xlabel('X Value')
plt.ylabel('Y Value')
plt.ylim(-1.5, 1.5)
plt.legend(loc='lower left')
# Save the plot to different formats
# Matplotlib infers the format from the extension
plt.savefig('sine_cosine_plot.png', dpi=300) # PNG: Raster format, good for web, dpi controls resolution
plt.savefig('sine_cosine_plot.pdf') # PDF: Vector format, good for documents, scales perfectly
plt.savefig('sine_cosine_plot.svg') # SVG: Vector format, good for web (scalable), editable
# It's good practice to close the plot figure after saving if you don't need to show it
plt.close()
print("Plots saved as sine_cosine_plot.png, sine_cosine_plot.pdf, and sine_cosine_plot.svg")
After running this, check your working directory for the saved files. Notice the difference:
dpi
(dots per inch) argument controls the resolution.These exercises cover the core techniques for polishing and saving plots. Don't hesitate to experiment further with different styles, colors, annotations, and layout adjustments. Effective visualization often involves iteration and refinement to best communicate your data's story.
© 2025 ApX Machine Learning