I do this
def example_plot(ax, somedata, somedata2, title, xlab, ylab, fontsize=12):
ax.plot(somedata, color='b')
ax.plot(somedata2, color='g')
ax.locator_params(nbins=3)
ax.set_xlabel(xlab, fontsize=8)
ax.set_ylabel(ylab, fontsize=10)
ax.set_title(title, fontsize=10)
import matplotlib.pyplot as plt
import numpy as np
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
ax1.grid(color='r', linestyle='-', linewidth=1)
ax2.grid(color='r', linestyle='-', linewidth=1)
ax3.grid(color='r', linestyle='-', linewidth=1)
ax4.grid(color='r', linestyle='-', linewidth=1)
example_plot(ax1,cumulative1,survival1, t1, xlbl1, ylbl1)
example_plot(ax2,cumulative2,survival2, t2, xlbl2, ylbl2)
example_plot(ax3,cumulative3,survival3, t3, xlbl3, ylbl3)
example_plot(ax4,cumulative4,survival4, t4, xlbl4, ylbl4)
plt.tight_layout(pad= 0.4, w_pad= 0.5, h_pad = 1.0)
My question revolves around applying custom xticks to every subplot. No matter how many times or where I place the lines
plt.xticks(np.arange(0,100, step = 10))
plt.xlim(0, 100)
They only wind up applying to the 4th subplot. How to define custom xticks for each subplot?
You have to apply the operations on the axes, plt manipulates the last axis used. You should read the documentation, what kind of manipulations you can perform on the Axes class. For your example, you would need set_xticks and set_xlim:
def example_plot(ax, somedata, somedata2, title, xlab, ylab, fontsize=12):
ax.plot(somedata, color='b')
ax.plot(somedata2, color='g')
ax.locator_params(nbins=3)
ax.set_xlabel(xlab, fontsize=8)
ax.set_ylabel(ylab, fontsize=10)
ax.set_title(title, fontsize=10)
import matplotlib.pyplot as plt
import numpy as np
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
ax1.grid(color='r', linestyle='-', linewidth=1)
ax2.grid(color='r', linestyle='-', linewidth=1)
ax3.grid(color='r', linestyle='-', linewidth=1)
ax4.grid(color='r', linestyle='-', linewidth=1)
example_plot(ax1,np.random.rand(10),np.random.rand(20), "A", "x A", "y A")
example_plot(ax2,np.random.rand(30),np.random.rand(40), "B", "x B", "y B")
example_plot(ax3,np.random.rand(10),np.random.rand(40), "C", "x C", "y C")
example_plot(ax4,np.random.rand(20),np.random.rand(50), "D", "x D", "y D")
plt.tight_layout(pad= 0.4, w_pad= 0.5, h_pad = 1.0)
ax1.set_xticks(range(0, 20, 5))
ax2.set_xlim(10, 40)
ax3.set_xlim(0, 50)
ax4.set_xticks(range(20, 50, 5))
plt.show()
Sample output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With