如何在Matplotlib中高效设置本地样式文本?含图文并排需求
更优实现方法
1. 无需LaTeX的带样式文本显示
Matplotlib原生支持解析HTML格式标签,无需启用LaTeX就能快速实现粗体、斜体样式,完全替代冗余的LaTeX命令:
import matplotlib.pyplot as plt plt.text(0, 0, '<b>This should be bold</b>, <i>this should be italics</i> and this should be a normal style.', fontsize=12) plt.show()
直接用<b>(粗体)、<i>(斜体)标签即可,默认配置下就能生效,速度远快于LaTeX渲染。
2. 绘图、带样式文本、表格并排布局方案
用GridSpec划分布局区域,分别在对应子区域添加绘图、文本和表格,无需手动计算位置,布局灵活可控:
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec # 创建1行3列的布局,调整各区域宽度比例 fig = plt.figure(figsize=(12, 5)) gs = GridSpec(1, 3, width_ratios=[2, 1, 1]) # 第一个区域:绘制图表 ax_plot = fig.add_subplot(gs[0]) ax_plot.plot([1,2,3], [4,5,1]) ax_plot.set_title('示例图表') # 第二个区域:显示带样式文本(隐藏坐标轴) ax_text = fig.add_subplot(gs[1]) ax_text.axis('off') ax_text.text(0.1, 0.5, '<b>This should be bold</b>, <i>this should be italics</i> and this should be a normal style.', fontsize=12, va='center') # 第三个区域:添加表格(隐藏坐标轴) ax_table = fig.add_subplot(gs[2]) ax_table.axis('off') # 表格数据 table_data = [['类别A', 10], ['类别B', 20], ['类别C', 15]] table = ax_table.table(cellText=table_data, colLabels=['名称', '数值'], loc='center') table.set_fontsize(12) plt.tight_layout() plt.show()
通过GridSpec的width_ratios可以自由调整各模块的宽度占比,文本区域隐藏坐标轴后完全作为纯文本展示区,表格直接通过table对象生成,样式和位置都能灵活调整。
内容的提问来源于stack exchange,提问作者Plop
相关产品推荐
相关产品推荐

