How to annotate text from one column onto a seaborn plot

一曲冷凌霜 提交于 2020-06-27 04:16:08

问题


I have a seaborn line plot denoting one column, but would like to annotate text from another column just above the value shown in the line. I can't seem to figure out the syntax. The code below is a replica of my dataframe. I would like to have the numbers from the 'flag' column annotated above the line of the group their observation corresponds to.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

d = {'group':[1,2,3,4,5,6,7,8,9,10]
    ,'y':[100,200,300,400,500,650,780,810,932,1050]
    ,'flag':[1503, 601, 348, 193, 161, 197, 322, 237, 85, 38]}
df = pd.DataFrame(d)
g = sns.lineplot(x = 'group', y = 'y', data = df).set_title('Example Graph')

回答1:


  • Use pandas.DataFrame.iterrows because it provides access to each x y value and the corresponding label.
  • Use matplotlib.pyplot.text to add the text label.
    • v[1][0] is the x location and v[1][1] is the y location.
    • Change the placement of the label by adding or subtracting from the x or y value.
      • x = v[1][0] - 0.2
      • y = v[1][1] + 14
  • See Python Data Science Handbook: Text and Annotation for additional options
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns


d = {'group': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
     'y': [100, 200, 300, 400, 500, 650, 780, 810, 932, 1050],
     'flag': [1503, 601, 348, 193, 161, 197, 322, 237, 85, 38]}
df = pd.DataFrame(d)
g = sns.lineplot(x = 'group', y = 'y', marker='.', data = df).set_title('Example Graph')

# add labels here
for v in df.iterrows():
    plt.text(v[1][0], v[1][1], f'{v[1][2]}')



来源:https://stackoverflow.com/questions/62331025/how-to-annotate-text-from-one-column-onto-a-seaborn-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!