2

I have a plot with a simple line. For the moment, I set yticks as invisible. enter image description here

Here is the code for the graph:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 1.5, 2, 2.5, 3]

fig, ax = plt.subplots(figsize=(15,10))
plt.plot(x, y, 'ko-')

plt.xlabel('X', fontsize=15)
plt.ylabel('Y', fontsize=15)
plt.xticks(x, fontsize=13)
plt.yticks(y, visible=False)

plt.margins(0.1, 0.1)
plt.title('Graph', color='black', fontsize=17) 
ax.axis('scaled') 
ax.grid()
plt.show()

I need to show/print yticks right on the graph itself (not on the left side). So, yticks are alongside with datapoints.

Desired output: enter image description here


How to do it with Matplotlib?

Erba Aitbayev
  • 4,167
  • 12
  • 46
  • 81

1 Answers1

2

You can use plt.text() to annotate text onto an axis. By iterating over your x,y points you can place a label at each marker. For example:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 1.5, 2, 2.5, 3]

fig, ax = plt.subplots(figsize=(15,10))
plt.plot(x, y, 'ko-')

plt.xlabel('X', fontsize=15)
plt.ylabel('Y', fontsize=15)
plt.xticks(x, fontsize=13)
plt.yticks(y, visible=False)

offset = 0.05
for xp, yp in zip(x,y):
    label = "%s" % yp
    plt.text(xp-offset, yp+offset, label, fontsize=12, horizontalalignment='right')

plt.margins(0.1, 0.1)
plt.title('Graph', color='black', fontsize=17) 
ax.axis('scaled') 
ax.grid()
plt.show()

Gives the following figure:

enter image description here

mfitzp
  • 15,275
  • 7
  • 50
  • 70