如何将Matplotlib折线图的图例设置为表格的行标签?
把折线图图例设为表格行标签的解决方案
嘿,这事儿好办!你只需要提取出折线图图例的文本内容,替换掉原来的'xxx'作为表格的行标签就行。下面是修改后的完整可运行代码:
import pandas as pd import numpy as np import matplotlib.pyplot as plt data = [4.6, 4.8, 4.7, 5.2, 5.3, 5.4, 5.5] index = ['3m','6m', '1year', '2year', '3year', '5year', '10year'] s = pd.Series(data, index=index) fig = plt.figure() ax = fig.add_subplot(111) x = np.arange(1, 8) pic = ax.plot(x, s) plt.xticks([]) # 创建图例并保存引用,注意用列表包裹文本避免被拆分 leg = plt.legend(['rate']) # 提取图例文本作为表格行标签 row_labels = [leg.get_texts()[0].get_text()] # 创建表格,使用图例文本作为行标签 table = ax.table( cellText=[data], colLabels=index, rowLabels=row_labels, loc='bottom' ) # 调整底部布局,避免表格遮挡折线图 plt.subplots_adjust(bottom=0.2) plt.show()
关键细节说明:
- 我把
plt.legend('rate')改成了plt.legend(['rate'])——直接传字符串会被拆分成单个字符当作多个图例项,用列表包裹才能正确显示完整的rate文本 - 通过
leg.get_texts()[0].get_text()可以精准提取图例的文本内容,把它赋值给表格的行标签参数 - 添加
plt.subplots_adjust(bottom=0.2)是为了给底部表格留出足够空间,防止和上方折线图重叠
内容的提问来源于stack exchange,提问作者Stephen Zhou
相关产品推荐
相关产品推荐

