如何用Matplotlib 2.1.0绘制指定Sin/Cos图并调整图例与布局?
Fixing Your Matplotlib Plot: Legend Customization & Plot Indent
Let's fix your code step by step, addressing all your requirements while correcting a small label mix-up in the original code (you had the cosine curve labeled as "sine" and vice versa):
Corrected & Customized Code
import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Generate 100 evenly spaced values from 0 to 2π x = np.linspace(0, 2 * np.pi, 100) # Initialize figure with specified size plt.figure(figsize=(10, 5)) # Set y-axis ticks plt.yticks(np.arange(-1, 1.25, 0.25)) # Set x-axis ticks plt.xticks(np.arange(0, 7, 1)) # Plot sine (blue) and cosine (red) curves with corrected labels plt.plot(x, np.sin(x), 'b', label="sine") plt.plot(x, np.cos(x), 'r', label="cosine") # Add x-axis label plt.xlabel('x (in radians)') # Customize legend to meet your needs plt.legend( loc=3, fontsize=8, # Shrink legend text size facecolor='lightgray', # Gray background for the legend box edgecolor='gray', # Gray border for the legend box frameon=True # Ensure the legend frame is visible ) # Add indent by adjusting plot margins plt.subplots_adjust(left=0.12, right=0.95, top=0.9, bottom=0.15) # Display the plot plt.show()
Key Modifications Explained
- Fixed Label Mismatch: Swapped the labels for the
sinandcoscurves so they correctly match the plotted functions. - Shrunken Legend: The
fontsize=8parameter reduces the size of the legend text. Adjust this value (e.g., 7, 9) to get your preferred size. - Gray Legend Box:
facecolor='lightgray'sets the legend's background to gray, whileedgecolor='gray'makes the border gray too. - Plot Indent:
plt.subplots_adjust()adjusts the margins around the plot area. Tweak theleft,right,top, andbottomvalues to control how much indent you want. - Consistent Pi Usage: Replaced
math.piwithnp.pito keep the code consistent with your NumPy-based workflow.
内容的提问来源于stack exchange,提问作者huda95x
相关产品推荐
相关产品推荐

