Matplotlib-Jupyter Notebook中如何添加颜色说明侧边小窗口?
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
locparameter sets where the legend is anchored relative to its own box (e.g.,'upper right','center left'). bbox_to_anchorlets 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

