Python matplotlib 中的粗体注释文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36162414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:30:04  来源:igfitidea点击:

bold annotated text in matplotlib

pythonmatplotlib

提问by simona

I want to make an annotated text in a plot using matplotlib. I have tried the following:

我想使用 matplotlib 在绘图中制作带注释的文本。我尝试了以下方法:

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

I have also tried:

我也试过:

 a=10.0
 text(0,1,":.2f".format(a), weight='bold')

None of they work.

他们都没有工作。



minimal example:

最小的例子:

import matplotlib.pyplot as plt

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

matplotlib version: 1.2.1

matplotlib 版本:1.2.1

python 3.3.2

蟒蛇 3.3.2

回答by Trenton McKinney

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'))

Annotate without bold

注释不加粗

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

Annotate with weight='bold'

注释与 weight='bold'

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

plt.show()

Final image:

最终图像:

enter image description here

在此处输入图片说明