簡體   English   中英

分別自定義matplotlib ticklabels

[英]customize matplotlib ticklabels individually

請考慮以下示例,在該示例中,我想將標簽“ C”的weight更改為bold

df = pd.DataFrame(data={'value': [3, 5, 7, 4, 5]},
                  index=list('ABCDE'))

fig, ax = plt.subplots()
df.plot.barh(ax=ax)

在此處輸入圖片說明

我見過許多示例(例如tick_paramsset_yticklabels )更改所有ticklabel或僅替換標簽而不進行格式化

有沒有一種方法可以單獨自定義它?

這是這樣做的一種方法:

  • 遍歷默認的刻度標簽,
  • 將所需標簽修改為黑體字
  • 重新分配刻度標簽。

from matplotlib import rc
import pandas as pd
import matplotlib.pyplot as plt

rc('text', usetex=True)

df = pd.DataFrame(data={'value': [3, 5, 7, 4, 5]},
                  index=list('ABCDE'))

fig, ax = plt.subplots()
df.plot.barh(ax=ax)

fig.canvas.draw()
new_labels = []
to_modify = 'C'

for lab in ax.get_yticklabels():
    txt = lab.get_text()
    if txt == to_modify:
        new_labels.append(r'$\textbf{%s}$' %txt) # append bold face text
    else:    
        new_labels.append(txt) # append normal text

ax.set_yticklabels(new_labels)        

在此處輸入圖片說明

ImportanceOfBeingEarnest建議的替代方法set_fontweight僅在不使用乳膠(TeX渲染)的情況下有效。

fig, ax = plt.subplots()
df.plot.barh(ax=ax)

to_modify = 'C'

for lab in ax.get_yticklabels():
    if lab.get_text() == to_modify:
      lab.set_fontweight('bold')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM