Set equal aspect in plot with colorbar

2024/9/29 9:30:48

I need to generate a plot with equal aspect in both axis and a colorbar to the right. I've tried setting aspect='auto', aspect=1, and aspect='equal' with no good results. See below for examples and the MWE.

Using aspect='auto' the colorbars are of the correct height but the plots are distorted:

enter image description here

Using aspect=1 or aspect='equal' the plots are square (equal aspect in both axis) but the colorbars are distorted:

enter image description here

In both plots the colorbars are positioned too far to the right for some reason. How can I get a square plot with colorbars of matching heights?


MWE

import numpy as np
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as pltdef col_plot(params):gs, i, data = paramsxarr, yarr, zarr = zip(*data)[0], zip(*data)[1], zip(*data)[2]xmin, xmax = min(xarr), max(xarr)ymin, ymax = min(yarr), max(yarr)#plt.subplot(gs[i], aspect='auto')plt.subplot(gs[i], aspect=1)#plt.subplot(gs[i], aspect='equal')plt.xlim(xmin, xmax)plt.ylim(xmin, xmax)plt.xlabel('$x axis$', fontsize=20)plt.ylabel('$y axis$', fontsize=20)# Scatter plot.cm = plt.cm.get_cmap('RdYlBu_r')SC = plt.scatter(xarr, yarr, marker='o', c=zarr, s=60, lw=0.25, cmap=cm,zorder=3)# Colorbar.ax0 = plt.subplot(gs[i + 1])cbar = plt.colorbar(SC, cax=ax0)cbar.set_label('$col bar$', fontsize=21, labelpad=-2)# Generate data.
data0 = np.random.uniform(0., 1., size=(50, 3))
data1 = np.random.uniform(0., 1., size=(50, 3))# Create the top-level container
fig = plt.figure(figsize=(14, 25))
gs = gridspec.GridSpec(4, 4, width_ratios=[1, 0.05, 1, 0.05])# Generate plots.
par_lst = [[gs, 0, data0], [gs, 2, data1]]
for pl_params in par_lst:col_plot(pl_params)# Output png file.
fig.tight_layout()
plt.savefig('colorbar_aspect.png', dpi=300)
Answer

You can use an AxesDivider to do that. I have modified your code a bit to make use of an AxesDivider.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatabledef col_plot(data):xarr, yarr, zarr = zip(*data)[0], zip(*data)[1], zip(*data)[2]xarr = [2*x for x in xarr]xmin, xmax = min(xarr), max(xarr)ymin, ymax = min(yarr), max(yarr)fig = plt.figure()ax0 = fig.add_subplot(111, aspect='equal')plt.xlim(xmin, xmax)plt.ylim(ymin, ymax)plt.xlabel('$x axis$', fontsize=20)plt.ylabel('$y axis$', fontsize=20)# Scatter plot.cm = plt.cm.get_cmap('RdYlBu_r')SC = ax0.scatter(xarr, yarr, marker='o', c=zarr, s=60, lw=0.25, cmap=cm,zorder=3)the_divider = make_axes_locatable(ax0)color_axis = the_divider.append_axes("right", size="5%", pad=0.1)# Colorbar.cbar = plt.colorbar(SC, cax=color_axis)cbar.set_label('$col bar$', fontsize=21, labelpad=-2)# Generate data.
data0 = np.random.uniform(0., 1., size=(20, 3))col_plot(data0)

And here is the result (I changed your data so it spans a range of [0, 2] in the x-direction for demonstration purposes):enter image description here

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

Related Q&A

How to emit dataChanged in PyQt5

The code below breaks on self.emit line. It works fine in PyQt4. How to fix this code so it works in PyQt5?from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QObject, pyqtSignalclass …

django: gettext and coercing to unicode

I have following code in my django application.class Status(object):def __init__(self, id, desc):self.id = idself.desc = descdef __unicode__(self):return self.descSTATUS = Status(0, _(u"Some text&…

Telegram bot api keyboard

I have problem with Telegram Bot Api and with "ReplyKeyboard". Im using Python 2.7 and I send post request:TelegramAPI.post(TELEGRAM_URL + "sendMessage", data=dict(chat_id=CHAT_ID, …

Use of torch.stack()

t1 = torch.tensor([1,2,3]) t2 = torch.tensor([4,5,6]) t3 = torch.tensor([7,8,9])torch.stack((t1,t2,t3),dim=1)When implementing the torch.stack(), I cant understand how stacking is done for different di…

Is it possible to sort a list with reduce?

I was given this as an exercise. I could of course sort a list by using sorted() or other ways from Python Standard Library, but I cant in this case. I think Im only supposed to use reduce().from funct…

Flask-WTF set time limit on CSRF token

Im currently using Flask-WTF v0.13.1, i have a few forms on my website, all created including the CSRF token.For some reasons i have to set a different expiration on each form, so far i could set manua…

Extracting Intermediate layer outputs of a CNN in PyTorch

I am using a Resnet18 model. ResNet((conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats…

In Tensorflow, how to unravel the flattened indices obtained by tf.nn.max_pool_with_argmax?

I meet a problem: After I use the tf.nn.max_pool_with_argmax, I obtain the indices i.e. argmax: A Tensor of type Targmax. 4-D. The flattened indices of the max values chosen for each output.How to unr…

How write csv file without new line character in last line?

I have a code like this to write csv file in python import csv with open(eggs.csv, wb) as csvfile:spamwriter = csv.writer(csvfile, delimiter= ,quotechar=|, quoting=csv.QUOTE_MINIMAL)spamwriter.writerow…

Getting tests to parallelize using nose in python

I have a directory with lots of .py files (say test_1.py, test_2.py and so on) Each one of them is written properly to be used with nose. So when I run nosetests script, it finds all the tests in all t…