Home > database >  Why is sharey = True ignored when adding facecolor?
Why is sharey = True ignored when adding facecolor?

Time:08-24

The two subplots generated by the code below share a common y-axis. However, once I add facecolor = "whitesmoke" , the option sharey = True is ignored. It is as if I had specified sharey = False. Any idea how I can combine facecolor with sharey = True?

import matplotlib.pyplot as plt
import numpy as np

# Some example data to display
x1 = np.linspace(0, 2 * np.pi, 400)
x2 = np.linspace(0, 2 * np.pi, 400)
y1 = np.sin(x1 ** 2)
y2 = np.sin(x2 ** 2) 
y2 = y2 1

fig, (ax1, ax2) = plt.subplots(1, 2, sharey = True)
fig.suptitle('Horizontally stacked subplots')
# ax1 = plt.subplot(121)
ax1 = plt.subplot(121, facecolor = "whitesmoke")
ax1 = plt.plot(x1,y1)
# ax2 = plt.subplot(122) 
ax2 = plt.subplot(122, facecolor = "whitesmoke") 
ax2 = plt.plot(x2,y2)
plt.
show()

Figure with facecolor and sharey = True

CodePudding user response:

What you are witnessing does not have anything to do with facecolor. You are defining your figure and axes properly with fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) but you overwrite your axes later by calling ax1 = plt.subplot(121, facecolor = "whitesmoke") and ax2 = .... Your axes are not sharing the y-axis anymore because you deleted the ones that did.

ax = plt.subplot(..., facecolor=...) is not meant to add a facecolor to an existing ax, it's meant to add a subplot to the current figure. Use ax.set_facecolor(...) instead:

enter image description here


import matplotlib.pyplot as plt
import numpy as np

# Some example data to display.
x1 = np.linspace(0, 2 * np.pi, 400)
x2 = np.linspace(0, 2 * np.pi, 400)
y1 = np.sin(x1 ** 2)
y2 = np.sin(x2 ** 2) 
y2 = y2 1

fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
fig.suptitle('Horizontally stacked subplots')
for ax in (ax1, ax2):
    ax.set_facecolor("whitesmoke")
ax1.plot(x1, y1)
ax2.plot(x2, y2)
fig.show()
  • Related