Issue
I have a hard time managing to add data labels to a matplotlib figure I'm creating. On bar graph I have no issue. For easier troubleshooting, I simplified it as much as possible but still with the same issue.
I've looked relentlessly but couldn't find the answer...
import matplotlib.pyplot as plt
dates = [10,11,12]
temp = [10,14,12]
temp_labels = plt.plot(dates,temp)
for x in temp_labels:
label = temp[x]
plt.annotate(label,
(x,temp[x]),
textcoords = "offset points"),
xytext = (0,10),
ha = "center")
plt.show()
I'm having an error:
Traceback (most recent call last):
File "rain_notif.py", line 16, in <module>
label = temp[x]
TypeError: list indices must be intergers or slices, not Line2D
Here is what I have and I just want to value label on top of each point. Figure without label
Solution
In your code temp_labels
is a list of lines, so x
is a line object, which cannot be used to index a list, as indicated by the error. Start from here:
import matplotlib.pyplot as plt
dates = [10,11,12]
temp = [10,14,12]
plt.plot(dates,temp)
for x, y in zip(dates, temp):
label = y
plt.annotate(str(label), (x, y),
xycoords="data",
textcoords="offset points",
xytext=(0, 10), ha="center")
plt.show()
Answered By - mcsoini
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.