Issue
I am trying to plot dataframe data in subplots, and I need to annotate each line with its label. Here is my current code:
legend = sorted(list(set([x[0] for x in multi.index.values])))
n = len(set([x[0] for x in multi.index]))
nc = [plt.get_cmap('turbo')(1. * i/n) for i in range(n)]
plt.rc('axes',prop_cycle=plt.cycler('color', nc))
fig, ax = plt.subplots(2, figsize=(15, 10))
plt.subplots_adjust(right=0.8)
ax[0].plot(multi.reset_index().pivot('A','B','C'))
ax0 = ax[0].twinx()
ax0.plot(multi.reset_index().pivot('A','B','C'), 'k:', lw=2)
ax[1].plot(multi.reset_index().pivot('A','B','D'))
ax1 = ax[1].twinx()
ax1.plot(multi.reset_index().pivot('A','B','D'), 'k:', lw=2)
fig.legend(legend)
plt.show()
How can I assign labels to each of the line in my subplot? I couldn't figure out to use plt.annotate()
so that it would add annotation for every line in the subplot.
Solution
I found a solution.
df = multi.reset_index().pivot('A','B','C')
for line, name in zip(ax[0].lines, df.columns):
y = line.get_ydata()[-1]
ax[0].annotate(name, xy=(1.05,y), size='small', xycoords=ax[0].get_yaxis_transform())
Repeating the same for the second subplot would also produce annotations for every line in the dataframe subplot.
Answered By - sowhatnowhuh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.