Polishing basic plots involves adding annotations, managing legends, adjusting layouts, applying themes, and saving work. Apply these techniques to make visualizations 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")Practice 1: Enhancing a Line PlotLet'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:Add Title and Labels: Give the plot a descriptive title and label the x and y axes.Customize Lines: Change the color and style of the lines to differentiate them clearly. Use names for colors (e.g., 'red', 'blue') or hex codes (e.g., '#1f77b4'). For styles, try '--' (dashed), ':' (dotted), or '-.' (dash-dot).Add a Legend: Include a legend to identify which line represents sin(x) and which represents cos(x). Experiment with loc values ('upper right', 'lower left', etc.) to find a good position.Set Axis Limits: Adjust the y-axis limits to range from -1.5 to 1.5 for better visual spacing.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.Practice 2: Adding Context to a Scatter PlotNow 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:Apply a Seaborn Theme: While we set a style earlier, try another one like sns.set_style("darkgrid") or sns.set_theme(style="ticks") before creating the plot to see the difference.Annotate a Point: Use plt.annotate() to add text pointing to the specific highlight_x, highlight_y point we defined earlier. Make the annotation informative.Adjust Layout: Sometimes elements like titles or annotations can overlap. Use 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 exerciseAnnotations help guide the viewer's attention to significant features within the data. plt.tight_layout() is a convenient function for basic layout adjustments.Practice 3: Refining a Bar ChartBar 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:Use a Seaborn Palette: Instead of the default single color, use a Seaborn color palette for the bars. You can pass a palette name (e.g., 'viridis', 'Blues_d') directly to Seaborn's barplot or assign colors manually in Matplotlib. Let's try using Seaborn's barplot for simplicity here.Add Value Labels: Add text above each bar showing its exact value. This often makes the chart easier to read than relying solely on the y-axis.Rotate X-axis Labels (if needed): If category names were longer, they might overlap. Although not strictly needed here, practice rotating them using 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.Practice 4: Saving Your Polished PlotFinally, 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:PNG: A pixel-based image. If you zoom in too much, it will look blocky. The dpi (dots per inch) argument controls the resolution.PDF/SVG: Vector-based formats. They describe the plot using shapes and lines. You can zoom in indefinitely without loss of quality. SVG is excellent for web use, while PDF is common for documents.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.