问题
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
xyvalue and the corresponding label. - Use matplotlib.pyplot.text to add the text label.
v[1][0]is the x location andv[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.2y = 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