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

Matplotlib-Jupyter Notebook中如何添加颜色说明侧边小窗口?

Answer

Absolutely, you can add that "side window"—it’s called a legend in Matplotlib, and it’s built specifically to explain what different colors, markers, or styles represent. Here’s how to implement it in your Jupyter Notebook:

Basic Inline Legend

If you’re plotting your red and green data directly, just add a label parameter to each plot call, then use plt.legend() to render the legend:

import matplotlib.pyplot as plt
import numpy as np

# Sample data for demonstration
x = np.linspace(0, 10, 100)
red_data = np.sin(x)
green_data = np.cos(x)

# Plot with descriptive labels
plt.plot(x, red_data, color='red', label='Red Data: Sine Wave')
plt.plot(x, green_data, color='green', label='Green Data: Cosine Wave')

# Add legend (defaults to a sensible position like upper right)
plt.legend()

plt.show()

Positioning the Legend Outside the Plot (Side Panel)

If you want the legend to sit outside the main plot area (like a dedicated side window), use the bbox_to_anchor parameter to adjust its position. For example, placing it to the right of the plot:

# Reuse the same data as above
plt.plot(x, red_data, color='red', label='Red Data: Sine Wave')
plt.plot(x, green_data, color='green', label='Green Data: Cosine Wave')

# Place legend outside the plot (right side)
plt.legend(loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0)

# Adjust layout to prevent legend from being cut off
plt.tight_layout()

plt.show()

For Scatter Plots or Other Plot Types

The same logic applies to any plot type—just add the label parameter to your scatter, bar, or histogram calls:

# Sample scatter data
red_points = np.random.rand(50, 2)
green_points = np.random.rand(50, 2) + 1

plt.scatter(red_points[:,0], red_points[:,1], color='red', label='Red Group: Cluster 1')
plt.scatter(green_points[:,0], green_points[:,1], color='green', label='Green Group: Cluster 2')

plt.legend(loc='lower right')
plt.show()

Key Tips:

  • The loc parameter sets where the legend is anchored relative to its own box (e.g., 'upper right', 'center left').
  • bbox_to_anchor lets you place the legend anywhere on the figure using coordinates relative to the plot axes.
  • plt.tight_layout() ensures the legend doesn’t get clipped when placed outside the plot bounds.

This should give you exactly the explanatory side window you’re looking for!

内容的提问来源于stack exchange,提问作者Aren Mark Boghozian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:35:00