Center the third subplot in the middle of second row python

2024/11/14 20:08:52

I have a figure consisting of 3 subplots. I would like to locate the last subplot in the middle of the second row. Currently it is located in the left bottom of the figure. How do I do this? I cannot find the answer on stack overflow.

    fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(13,10))ax= axes.flatten()ax[0].plot(vDT, np.cumsum(mWopt0[asset0,:])*percentage/iTT, label= 'COAL, c = 0')ax[0].legend()ax[0].set_title('Proportion in most invested stock')ax[1].plot(vDT, np.cumsum(mWopt01[asset01,:])*percentage/iTT, label= 'OINL, c = 0.1')ax[1].plot(vDT, np.cumsum(mWopt03[asset03,:])*percentage/iTT, label= 'OINL, c = 0.3')ax[1].plot(vDT, np.cumsum(mWopt05[asset05,:])*percentage/iTT, label= 'OINL, c = 0.5')ax[1].plot(vDT, np.cumsum(mWopt2[asset2,:])*percentage/iTT, label= 'OINL, c = 2')ax[1].plot(vDT, np.cumsum(mWopt5[asset5,:])*percentage/iTT, label= 'OINL, c = 5')ax[1].plot(vDT, np.cumsum(mWopt10[asset10,:])*percentage/iTT, label= 'OINL, c = 10')ax[1].legend()ax[1].set_title('Proportion in most invested stock')ax[2].plot(vDT, np.cumsum(mWopt01[index,:])*percentage/iTT, label= 'c = 0')ax[2].plot(vDT, np.cumsum(mWopt01[index,:])*percentage/iTT, label= 'c = 0.1')ax[2].plot(vDT, np.cumsum(mWopt03[ index,:])*percentage/iTT, label= 'c = 0.3')ax[2].plot(vDT, np.cumsum(mWopt05[index,:])*percentage/iTT, label= 'c = 0.5')ax[2].plot(vDT, np.cumsum(mWopt2[index,:])*percentage/iTT, label= 'c = 2')ax[2].plot(vDT, np.cumsum(mWopt5[index,:])*percentage/iTT, label= 'c = 5')ax[2].plot(vDT, np.cumsum(mWopt10[index,:])*percentage/iTT, label= 'c = 10')ax[2].legend()ax[2].set_title('Proportion invested in index')ax[0].set_ylabel('Expanding window weight')ax[1].set_ylabel('Expanding window weight')ax[2].set_ylabel('Expanding window weight')ax[3].remove()fig.autofmt_xdate(bottom=0.2, rotation=75, ha='right')plt.savefig('NSE_por_unrestricted_mostweightSI.jpg', bbox_inches='tight')plt.show()
Answer

matplotlib.gridspec.Gridspec solves your problem, and can be passed to plt.subplot. In this answer, you can see that a 4x4 grid can be used to position a plot in the middle easily:

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as pltgs = gridspec.GridSpec(4, 4)ax1 = plt.subplot(gs[:2, :2])
ax1.plot(range(0,10), range(0,10))ax2 = plt.subplot(gs[:2, 2:])
ax2.plot(range(0,10), range(0,10))ax3 = plt.subplot(gs[2:4, 1:3])
ax3.plot(range(0,10), range(0,10))plt.show()

You can check out the demos for gridspec here: https://matplotlib.org/tutorials/intermediate/gridspec.html#sphx-glr-tutorials-intermediate-gridspec-py

The only problem is that you are using the fig, axes = pattern, which I don't see being typically used with Gridspec. You would need to refactor a bit.

https://en.xdnf.cn/q/71464.html

Related Q&A

Removing columns which has only nan values from a NumPy array

I have a NumPy matrix like the one below:[[182 93 107 ..., nan nan -1][182 93 107 ..., nan nan -1][182 93 110 ..., nan nan -1]..., [188 95 112 ..., nan nan -1][188 97 115 ..., nan nan -1][188 95 112 ..…

how to get kubectl configuration from azure aks with python?

I create a k8s deployment script with python, and to get the configuration from kubectl, I use the python command:from kubernetes import client, configconfig.load_kube_config()to get the azure aks conf…

Object vs. Dictionary: how to organise a data tree?

I am programming some kind of simulation with its data organised in a tree. The main object is World which holds a bunch of methods and a list of City objects. Each City object in turn has a bunch of m…

Fastest way to compute distance beetween each points in python

In my project I need to compute euclidian distance beetween each points stored in an array. The entry array is a 2D numpy array with 3 columns which are the coordinates(x,y,z) and each rows define a ne…

Calling C from Python: passing list of numpy pointers

I have a variable number of numpy arrays, which Id like to pass to a C function. I managed to pass each individual array (using <ndarray>.ctypes.data_as(c_void_p)), but the number of array may va…

Use of initialize in python multiprocessing worker pool

I was looking into the multiprocessing.Pool for workers, trying to initialize workers with some state. The pool can take a callable, initialize, but it isnt passed a reference to the initialized worker…

Pandas: select the first couple of rows in each group

I cant solve this simple problem and Im asking for help here... I have DataFrame as follows and I want to select the first two rows in each group of adf = pd.DataFrame({a:pd.Series([NewYork,NewYork,New…

Pandas: Approximate join on one column, exact match on other columns

I have two pandas dataframes I want to join/merge exactly on a number of columns (say 3) and approximately, i.e nearest neighbour, on one (date) column. I also want to return the difference (days) betw…

Adding a variable in Content disposition response file name-python/django

I am looking to add a a variable into the file name section of my below python code so that the downloaded files name will change based on a users input upon download. So instead of "Data.xlsx&quo…

TkInter: understanding unbind function

Does TkInter unbind function prevents the widget on which it is applied from binding further events to the widget ?Clarification:Lets say I bound events to a canvas earlier in a prgram:canvas.bind(&qu…