Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning x-axis with sharex using subplots and colorbar with matplotlib

I'm trying to create a set of subplots with a shared x axis using pyplot. This is all fine and dandy when the graphs are simple and all the x-axes align fine. However when I include a subplot that includes a colorbar, this compresses the width of that particular subplot to include the colorbar, resulting in the subplots no longer sharing the x-axis.

I've searched the web with no success with this. I've tried several different methods, but the simplest example I include below. I plot the exact same data in each subplot, but plot one with a colorbar. You can see the data no longer align along the x-axis.

Thanks in advance for your help!


import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import pandas as pd

x = np.linspace(0, 10, num=100)
y = x ** 2 + 10 * np.random.randn(100)


f, (ax1, ax2) = plt.subplots(2,1,sharex=True,figsize=(8,12))

im1 = ax1.scatter(x, y, c=y, cmap='magma')
divider = make_axes_locatable(ax1)
cax = divider.append_axes("right", size="5%", pad=.05)

plt.colorbar(im1, cax=cax)

im2 = ax2.plot(x, y,'.')

plt.show()

Plot that I can't embed

like image 930
user3317621 Avatar asked Feb 01 '19 05:02

user3317621


People also ask

How do I change the X-axis values in MatPlotLib?

The xticks() function in pyplot module of the Matplotlib library is used to set x-axis values. List of xticks locations. Passing an empty list will remove all the xticks.


2 Answers

Suggest using constrained_layout=True: https://matplotlib.org/stable/tutorials/intermediate/constrainedlayout_guide.html

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, num=100)
y = x ** 2 + 10 * np.random.randn(100)

f, (ax1, ax2) = plt.subplots(2,1,sharex=True,figsize=(8,12),
        constrained_layout=True)
im1 = ax1.scatter(x, y, c=y, cmap='magma')
f.colorbar(im1, ax=ax1)
im2 = ax2.plot(x, y,'.')

enter image description here

like image 189
Jody Klymak Avatar answered Sep 28 '22 16:09

Jody Klymak


This is one hacky way to do it.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import pandas as pd

x = np.linspace(0, 10, num=100)
y = x ** 2 + 10 * np.random.randn(100)


f, (ax1, ax2) = plt.subplots(2,1,sharex=True,figsize=(8,12))

im1 = ax1.scatter(x, y, c=y, cmap='magma')
divider = make_axes_locatable(ax1)
cax = divider.append_axes("right", size="5%", pad=.05)

plt.colorbar(im1, cax=cax)

im2 = ax2.plot(x, y,'.')
divider2 = make_axes_locatable(ax2)
cax2 = divider2.append_axes("right", size="5%", pad=.05)
cax2.remove()
plt.show()

results in

enter image description here

like image 44
plasmon360 Avatar answered Sep 28 '22 15:09

plasmon360