Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force all subplots to use the same axis range when plotting with Pandas

I'm using the "by" option to create facet plots with Pandas like the following:

import pandas as pd
pd.Series(randn(1000)).hist(by=randint(0, 4, 1000), figsize=(6, 4))

enter image description here

Which is great. However I want both the x and y axis to be the same across all plots. Is there a built in way to do this? In ggplot I would use the scales="fixed" option but I don't see something like that built into the Pandas plotting.

Obviously my fallback is to write a few short lines that does this for me, but if there's an automagic way to do this, I'd like to use it.

like image 432
JD Long Avatar asked Feb 12 '23 01:02

JD Long


1 Answers

You are looking for shared x- and y-axes which can be enabled by passing sharex=True and sharey=True as keyword arguments to hist.

This creates the subplots via matplotlib's subplot machinery. The upside of this as opposed to manually positioning subplots and removing axes is that you can use a large matplotlib toolset to manipulate the axes, e.g.

import matplotlib.pyplot as plt
import pandas as pd
pd.Series(randn(1000)).hist(by=randint(0, 4, 1000), figsize=(6, 4),
                            sharex=True, sharey=True)

ax = plt.gca()
ax.set_xlim(-10, 10)
ax.set_ylim(0, 100)

example with some axis properties set

like image 199
Benjamin Bannier Avatar answered Feb 15 '23 02:02

Benjamin Bannier