繁体   English   中英

使用 matplotlib 在绘图脚本中设置 Latex 希腊字母

[英]Set Latex greek letter in plotting script using matplotlib

我有一个绘图脚本,我从 JSON 文件加载字幕(变量subplot_titles ):

JSON 文件示例:

"subplot_titles" : {

    "0" : "Model: $~w_{0},~w_{a}~$ - flat - optimistic - No $\\gamma$",
    "1" : "Model: $~w_{0},~w_{a}~$ - flat - optimistic - With $\\gamma$",
    "2" : "Model: $~w_{0},~w_{a}~$ - flat - semi-pessimistic - No $\\gamma$",
    "3" : "Model: $~w_{0},~w_{a}~$ - flat - semi-pessimistic - With $\\gamma$"
},

在我的脚本中,我像这样加载这个文件:

 for i, ax in enumerate(np.ravel(axes)):

    config = load_config('./config.json')

    df = parse_input(config['subplot_files'][i])
    df = format_dataframe(df, config)
    title = config['subplot_titles'][i]
    lgd = plot_barchart(df, ax, title)
    bbea.append(lgd)

但是一旦生成了图形,我就有了一个丑陋的符号“gamma”,如下所示:

坏伽玛

我想显示一个 Latex 伽玛符号。

我尝试在绘图脚本中添加r'以获得 Latex 支持:

title = config[r'subplot_titles'][i]

但我得到一个错误。

谁能看到在 Latex 显示下我能做些什么来获取这个伽玛希腊符号?

更新:

给出的解决方案有效,但我想保留 matplotlib 字体以显示在 jSON 文件中的表格下:

“酒吧”:{

"0" : "$GC_{s}$",
"1" : "$GC_{ph} + WL$",
"2" : "$GC_{s} + GC_{ph} + WL$",
"3" : "$GC_{ph} + WL + XC$",
"4" : "$GC_{s} + (GC_{ph} + WL + XC)$",
"5" : "($GC_{s} + GC_{ph} + WL) + XC2$",
"6" : "$GC_{s} + (GC_{ph} + WL + XC) + XC2$"

},

这产生了一个很好的传说:

想要的结果

For the subplot_titles , I have just to replace a greek symbol by the Latex equivalent but caution, with the real Latex symbol \gamma , not the one which makes part of Latex of matplotlib like the uggly "\gamma" symbol I have shown above,并将所有 rest 保持原样。

我试图做这个替代:

title = title.replace("\\gamma", "+r\"\\mathit{\\gamma}")

但没有成功...

如何执行此渲染?

您可以更改 matplotlib rc 设置以使用 LaTeX,例如在开始绘图之前包含以下代码:

import matplotlib as mpl
mpl.rcParams['text.usetex'] = True

或者,您可以更改 matplotlib 用于排版数学的字体,而不是使用 LaTeX:

mpl.rcParams['mathtext.fontset'] = 'cm'

'cm'是 Computer Modern,默认 LaTeX 字体,但也有其他可能

您可以在第一个轴上覆盖第二个Axes ,使所有标签和脊椎不可见,以便仅将此轴用于标题的“gamma”部分。 然后原始轴的标题将是没有\gamma的实际标题,第二个轴的标题将仅包含\gamma并接收所需的数学字体系列(例如'cm' )。 困难的部分是对齐两个标题,使第二个是 position 紧挨第一个。 在下面的示例中,我对位置进行了硬编码,因此这仅适用于给定的图形大小。 我没有找到让它自动调整的方法,但这个问题的答案可能有助于进一步探索该选项。

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5,3))
ax.set_title(r"$w_{0},w_{a}$ - flat - optimistic - with ", position=(0.5, 1.0))

newax = fig.add_axes(ax.get_position())
newax.patch.set_visible(False)
newax.xaxis.set_visible(False)
newax.yaxis.set_visible(False)
newax.set_title(r'$\gamma$', position=(0.845, 1.0)).set_math_fontfamily('cm')

ax.plot([1, 2], [1, 2], 'r-', label=r"$GC_s$")
ax.plot([1, 2], [3, 1], 'b--', label=r"$GC_{ph} + WL$")
ax.plot([1, 2], [2, 0], 'g-.', label=r"$GC_s + GC_{ph} + WL$")
ax.legend()
plt.show()

产生以下 plot:

示例图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM