[英]Does Matplotlib have an incomplete set of Greek characters in its 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.