2

I have the following piece of code which creates a simple plot with matplotlib (python 3.6.9, matplotlib 3.1.2, Mac Mojave):

import numpy as np
import matplotlib.pyplot as plt

plt.imshow(np.random.random((50,50)))
plt.show()

The created plot is as expected:

enter image description here

Now, in order to relabel the xtick/ytick labels I am using the following code

import numpy as np
import matplotlib.pyplot as plt

plt.imshow(np.random.random((50,50)));

ticks, labels = plt.xticks()
labels[1] = '22'
plt.xticks(ticks, labels)

plt.show()

where I expect the second label to be replaced by '22', but everything else stays the same. However, I get the following plot instead:

enter image description here

  1. There is some unexpected white area in the left part of the plot
  2. All the other labels have vanished.

How to do it correctly?

Just as a reminder: I want to get the exact same result as the original image (first plot), ONLY with one of the lables changed.

This question has been asked before, one example is here. But the answer does not seem to work. Here is the code

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
plt.imshow(np.random.random((50,50)))

labels = [item.get_text() for item in ax.get_xticklabels()]
labels[1] = 'Test'
ax.set_xticklabels(labels)

plt.show()

which creates an image as follows:

enter image description here

which does not show the white area anymore, but still the other labels are not shown.

Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

3

Create axes using subplots, so that you can have set_xticklabels method, so you can update the labels.

You need to use, canvas.draw() to get the values.

import numpy as np
import matplotlib.pyplot as plt

fig,ax = plt.subplots()
ax.imshow(np.random.random((50,50)));
fig.canvas.draw()
#labels = ['-10','0','22','20','30','40'] or
labels[2]=22
ax.set_xticklabels(labels)

plt.show()

Output:

Output image

Hope this is what you need!

Strange
  • 1,460
  • 1
  • 7
  • 18
  • No, you did not understand what I want. I want the original plot, and instead where the number '10' is written on the x-axis, I want that number '10' replaced - at the exact same location, with something else. Just something else. – Alex Jan 18 '20 at 08:28
  • Got it! I'll update my answer soon! – Strange Jan 18 '20 at 08:30
  • Check the updated answer. – Strange Jan 18 '20 at 08:49
  • Thanks, but in that case I have to 'guess' the other labels? Can't that be done automatically? Why do I have to redefine the existing labels? It works fine for the example,. but when I use a different plot, scale etc that does not work. Do I have to 'try' all the time then? – Alex Jan 18 '20 at 10:21
  • Check the edit, you can do it by using canvas.draw() to retrieve the existing labels. if you don't use it, then all zeros are shown. – Strange Jan 18 '20 at 14:03