legend多个图例一次输出

lgd = num2str((1:6)','第%d条路径');
legend(lgd)

这里写图片描述

### 绘制多条折线图并共享同一图例的方法 在 Python 的 `matplotlib` 和 `seaborn` 中,可以通过设置参数和操作句柄来实现多条折线图共享同一个图例的功能。以下是具体实现方式: #### 使用 Matplotlib 实现 通过 `plt.plot()` 方法绘制每一条折线,并传递标签参数 `label` 来定义每一类数据的名称。最后调用 `plt.legend()` 函数即可生成统一的图例。 ```python import matplotlib.pyplot as plt import numpy as np # 创建示例数据 x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # 绘制第一条折线 plt.plot(x, y1, label='Sine Wave') # 绘制第二条折线 plt.plot(x, y2, label='Cosine Wave') # 添加图例 plt.legend() # 设置标题和坐标轴标签 plt.title('Multiple Lines with Shared Legend') plt.xlabel('X-axis') plt.ylabel('Y-axis') # 显示图像 plt.show() ``` 上述代码中,两条折线分别被赋予了不同的标签 `'Sine Wave'` 和 `'Cosine Wave'`[^1]。最终通过 `plt.legend()` 将其合并到一个图例中。 --- #### 使用 Seaborn 实现 Seaborn 是基于 Matplotlib 构建的一个高级绘图库,在处理复杂图表时更加简洁直观。对于多条折线图的情况,可以利用 `sns.lineplot()` 并传入分类变量作为颜色区分依据。 ```python import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt # 创建 DataFrame 数据结构 data = { 'x': list(range(10)) * 2, 'y': [*np.random.randn(10), *np.random.randn(10)], 'category': ['Line A'] * 10 + ['Line B'] * 10 } df = pd.DataFrame(data) # 使用 Seaborn 进行绘图 sns.lineplot(data=df, x='x', y='y', hue='category') # 利用 hue 参数指定类别 # 自定义标题和其他属性 plt.title('Shared Legend Using Seaborn Lineplot') plt.xlabel('X-axis') plt.ylabel('Y-axis') # 展示结果 plt.show() ``` 在此代码片段中,`hue='category'` 参数自动为不同类别的线条分配颜色,并将其纳入单一图例之中[^2]。 --- #### 结合柱状图与折线图 当需要在同一张图表上展示柱状图和折线图时,可采用双轴技术或将两者叠加于单个坐标系下。以下是一个综合案例演示如何使两种类型的图形共存且拥有共同的图例说明。 ```python import matplotlib.pyplot as plt import numpy as np # 定义数据集 labels = ['G1', 'G2', 'G3', 'G4', 'G5'] bar_data = [20, 35, 30, 35, 27] line_data = [25, 32, 34, 20, 25] x = np.arange(len(labels)) fig, ax1 = plt.subplots() # 绘制柱状图 ax1.bar(x, bar_data, color='lightblue', edgecolor='black', label='Bar Data') # 同一坐标系下添加折线图 ax1.plot(x, line_data, marker='o', linestyle='-', color='red', linewidth=2, label='Line Data') # 配置 X 轴刻度位置及其标签文字方向 ax1.set_xticks(x) ax1.set_xticklabels(labels) # 增加网格辅助阅读数值关系 ax1.grid(True, which='both', axis='y', linestyle='--', alpha=0.6) # 图例放置最佳适配区域 handles, labels = ax1.get_legend_handles_labels() ax1.legend(handles, labels, loc="upper left") # 设定其他样式选项 ax1.set_title('Combination of Bar and Line Charts Sharing One Legend') ax1.set_xlabel('Categories') ax1.set_ylabel('Values') # 输出图片 plt.tight_layout() plt.show() ``` 此脚本展示了如何在一个坐标平面上同时呈现柱状图和折线图,并确保两者的描述项能够整合进唯一的图例列表里[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VeeeNus

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值