2

I'd like to manipulate the ticks of every plot in my subplots. When plotting a single plot I get the desired result by using:

import matplotlib.pyplot as plt
import numpy as np

# ...
# some data acquisition
# ...

ax.imshow(data[i], cmap=plt.cm.jet, origin='bottom')
ax.contour(x, y, dataFitted[i].reshape(2*crop, 2*crop), 3, colors='white')

# adjust scale from pixel to micrometers on heat maps
pixelSize = 5.5 # micrometer/pxl
scaleEnd = crop * pixelSize
wishedTicks = np.array([-150, -100, -50, 0, 50, 100, 150])
originalTicks = (wishedTicks + scaleEnd) / pixelSize

plt.xticks(originalTicks, wishedTicks)
plt.yticks(originalTicks, wishedTicks)

So far, so good, but if I use

fig, ax = plt.subplots(nrows=5, ncols=4)

to create subplots, the function plt.xticks() is not available any more to my understanding.

Is there a way to receive the same result by

  • either globally (for all figures) manipulating the axis in the same way I did for a single plot

or

  • manipulating each subplot individually in the desired way as above?
Felix
  • 83
  • 9

2 Answers2

2

Always work with an explicit axes, for plotting, as for setting the ticks/labels.

fig, axs = plt.subplots(5,4, figsize=(9,7))

for ax in axs.flat:
    ax.plot(...)
    ax.set_xticks(ticks)
    ax.set_xticklabels(labels)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

Using plt.subplot (documentation) instead of plt.subplots might suit your needs.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
x_labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k']
y = np.arange(0, 20, 2)

for i in range(1, 5):
        ax = plt.subplot(2, 2, i)
        plt.plot(x, y)
        plt.xticks(x, x_labels)

plt.show()

Produces this: output

Also recommend reading this article on subplots to see some more neat stuff you can do with them.

alon-k
  • 330
  • 2
  • 11
  • Thanks, it worked so far. Can you tell me if it is possible to increase the figure size for all subplots, as everything is crunched together tightly. I did only find solutions where one has an attributed figure object like e.g. f, ax = fig.subplots(a, b, figsize(1,1)). – Felix Sep 21 '19 at 12:01
  • `fig.subplots_adjust(hspace=0.4, wspace=0.4)` should work. You can play with the values. – alon-k Sep 21 '19 at 13:10
  • 1
    but @ImportanceOfBeingErnest 's answer is probably better. I just didn't remember how to do that explicitly with the axes (`.xticks` didn't work) – alon-k Sep 21 '19 at 13:12
  • you can try plt.tight_layout() and see if it improves the spacing between the subplots – Sultan Singh Atwal Oct 05 '19 at 15:40