tal
tal

Reputation: 960

Showing both the value and index in the x-ticks in a plot

I want to plot something using plot(x,y) and be able to see on the plot the index of the value in x

For example.

x = [10,30,100,120]
y = [16,17,19,3]
plot(x,y)

will show

enter image description here

looking at the plot it is hard to know at every point what was the original index. For example I want to be able to know when looking at the point (100,19) that it is index 2, since x[2]=100 and y[2]=19. How do I do that in matplotlib. I looked at twiny() function but that seems to just add another axes disregarding the distance between points in x.

Upvotes: 1

Views: 92

Answers (1)

Andreq
Andreq

Reputation: 417

Here's my solution:

import matplotlib.pyplot as plt
x = [10,30,100,120]
y = [16,17,19,3]
plt.plot(x,y);
for i, (a, b) in enumerate(zip(x, y)):
    plt.annotate(str(i), xy=(a, b), textcoords="offset points", xytext=(0, 12),
                 horizontalalignment='center', verticalalignment='center')
plt.xlim(0, 130)
plt.ylim(0, 22)

What it does: it enumerates on your y and x arrays, storing the index in the variable i and the respective values of x and y in the variables a and b. It then annotates the index i at the coordinates (a, b), offsetting the text by 12 pixels on the y-axis to avoid the annotation covering the curve.

The result:

enter image description here

Upvotes: 1

Related Questions