0

I am building a line chart with x axis categorical variables and two y axis with continuous variables. I want to annotate each data points on each line with their corresponding y axis values. The following chart shows what I want except the red hand-written numbers are what I am missing now. enter image description here I have tried to annotate the value for ax1 which is the primary axis with the code

for i, txt in enumerate(np.array(aaa_1).reshape(1,3)[0]):
    ax1.annotate(txt, (x_ax[i], np.array(aaa_1).reshape(1,3)[0][i]))

but I don't know how to annotate the rest lines as they are all under ax2.

aaa = pd.DataFrame([['a', 100, 1,4], ['b', 478, 3,3], ['c', 700, 9,5]], index=[1, 2, 3],
                  columns=['col a', 'col b', 'col c','col d'])
aaa_1 = aaa.iloc[:,1:2]
qqq_2 = aaa.iloc[:,[2]]
qqq_3 = aaa.iloc[:,[3]]
x_ax = np.array(aaa['col a'])

fig, ax1 = pl.subplots()
ax1.set_xlabel('col a')
ax1.set_ylabel('Value')
lns1= ax1.plot(x_ax, aaa_1, label= 'col b', color = 'C6')
ax1.tick_params(axis='y')
ax1.set_ylim(50,800)

for i, txt in enumerate(np.array(aaa_1).reshape(1,3)[0]):
    ax1.annotate(txt, (x_ax[i], np.array(aaa_1).reshape(1,3)[0][i]))

ax2 = ax1.twinx()

ax2.set_ylabel('Height')  # we already handled the x-label with ax1
lns2 = ax2.plot(x_ax, qqq_2, label= 'col c', color = 'C1')
lns3 = ax2.plot(x_ax, qqq_3, label= 'col d', color = 'C5')
ax2.tick_params(axis='y')
ax2.set_ylim(0,12)


lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax1.legend(lns, labs, loc=0)


fig.tight_layout()  # otherwise the right y-label is slightly clipped
pl.show()

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Philip Chen
  • 149
  • 2
  • 8
  • It might help to review [`matplotlib`'s large tutorial on annotating plots in a bunch of different ways](https://matplotlib.org/gallery/text_labels_and_annotations/annotation_demo.html?highlight=annotate) – Reedinationer Apr 18 '19 at 20:58
  • 1
    To annotate points in ax2 you can use `ax2.annotate(..)`, so it's not really clear what problem you face. – ImportanceOfBeingErnest Apr 18 '19 at 21:04
  • @ImportanceOfBeingErnest Thanks for your answer. My problem here is that there are 2 lines under the ax2 (the brown and yellow ones). If I use ```ax2.annotate(..)``` to add the label, it will only tag one of those two lines, not tagging both respectively. – Philip Chen Apr 26 '19 at 18:40
  • 1
    Yeah, you need that part twice, one `annotate` for each line with different data of course. – ImportanceOfBeingErnest Apr 27 '19 at 02:29

0 Answers0