You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 sin and cos curves so they correctly match the plotted functions.
  • Shrunken Legend: The fontsize=8 parameter 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, while edgecolor='gray' makes the border gray too.
  • Plot Indent: plt.subplots_adjust() adjusts the margins around the plot area. Tweak the left, right, top, and bottom values to control how much indent you want.
  • Consistent Pi Usage: Replaced math.pi with np.pi to keep the code consistent with your NumPy-based workflow.

内容的提问来源于stack exchange,提问作者huda95x

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:05:16