matplotlib中的粗体注释文本

sim*_*ona 15 python matplotlib

我想使用matplotlib在一个图中做一个带注释的文本.我尝试过以下方法:

 a=10.0
 font=matplotlib.font_manager.FontProperties()
 font.set_weight('bold')
 text(0,1,":.2f".format(a), fontproperties=font)
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

 a=10.0
 text(0,1,":.2f".format(a), weight='bold')
Run Code Online (Sandbox Code Playgroud)

他们都没有工作.


最小的例子:

import matplotlib.pyplot as plt

def main():
   plt.figure()
   plt.plot([0,1],[0,1])
   plt.text(0.5,0.5,"string",weight="bold")
Run Code Online (Sandbox Code Playgroud)

matplotlib版本:1.2.1

python 3.3.2

Tre*_*ney 20

  • 添加注释/文本也适用于seaborn使用相同方法的轴级绘图。
    • 对于seaborn图形级别的图,您必须遍历未显示的每个轴。
  • 可以使用.text或指定粗体文本.annotate

导入、数据帧和绘图设置

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
    
swing = pd.read_csv('https://assets.datacamp.com/production/repositories/469/datasets/e079fddb581197780e1a7b7af2aeeff7242535f0/2008_swing_states.csv')
    
plt.figure(figsize=(10,10))
sns.scatterplot(x='total_votes', y='dem_share', data=swing, hue='state')
plt.xlabel('total votes')
plt.ylabel('% of vote for Obama')
plt.xticks([x for x in range(0, 1000000, 100000)], rotation=40)
plt.yticks([x for x in range(0, 100, 10)])
    
# Create a Rectangle patch
plt.gca().add_patch(Rectangle((400000, 52), 500000, 34, linewidth=1, edgecolor='b', facecolor='none'))
    
plt.gca().add_patch(Rectangle((0, 5), 50000, 45, linewidth=1, edgecolor='r', facecolor='none'))
Run Code Online (Sandbox Code Playgroud)

添加注释

.annotate 没有粗体

plt.annotate('12 largest counties; most vote for Obama', xy=(650000, 52),
             xytext=(400000, 35), fontsize=10, arrowprops=dict(arrowstyle="->", color='b'))
Run Code Online (Sandbox Code Playgroud)

.annotateweight='bold'

plt.annotate('small counties; most vote for McCain', xy=(50000, 20), weight='bold',
             xytext=(150000, 7), fontsize=10, arrowprops=dict(arrowstyle="->", color='r'))
Run Code Online (Sandbox Code Playgroud)

.textweight='bold'

plt.annotate('12 largest counties; most vote for Obama', xy=(650000, 52),
             xytext=(400000, 35), fontsize=10, arrowprops=dict(arrowstyle="->", color='b'))
Run Code Online (Sandbox Code Playgroud)

最终图像:

在此处输入图片说明

原始 MRE

  • 也许当时有一个错误,但是来自 OP 的 MRE 可以正常工作。
plt.annotate('small counties; most vote for McCain', xy=(50000, 20), weight='bold',
             xytext=(150000, 7), fontsize=10, arrowprops=dict(arrowstyle="->", color='r'))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明