Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: Can we draw a histogram and a box plot on a same chart?

I have a question about drawing a histogram and a box plot Matplotlib.

I know I can draw a histogram and a box plot individually. My question is, is it possible to draw them on the same graph, such as a chart shown in this website? Springer Images

Thank you very much!

like image 341
Kotaro Avatar asked Apr 24 '26 08:04

Kotaro


2 Answers

There are several ways to achieve this with matplotlib. The plt.subplots() method, and the AxesGrid1 and gridspec toolkits all provide very elegant solutions, but might take time to learn.

A simple, brute-force way to do this would be to manually add the axes objects to a figure yourself.

import numpy as np
import matplotlib.pyplot as plt

# fake data
x = np.random.lognormal(mean=2.25, sigma=0.75, size=37)

# setup the figure and axes
fig = plt.figure(figsize=(6,4))
bpAx = fig.add_axes([0.2, 0.7, 0.7, 0.2])   # left, bottom, width, height:
                                            # (adjust as necessary)
histAx = fig.add_axes([0.2, 0.2, 0.7, 0.5]) # left specs should match and
                                            # bottom + height on this line should
                                            # equal bottom on bpAx line
# plot stuff
bp = bpAx.boxplot(x, notch=True, vert=False)
h = histAx.hist(x, bins=7)

# confirm that the axes line up 
xlims = np.array([bpAx.get_xlim(), histAx.get_xlim()])
for ax in [bpAx, histAx]:
    ax.set_xlim([xlims.min(), xlims.max()])

bpAx.set_xticklabels([])  # clear out overlapping xlabels
bpAx.set_yticks([])  # don't need that 1 tick mark
plt.show()
like image 142
Paul H Avatar answered Apr 26 '26 22:04

Paul H


Yes and the best way I've seen to handle this can be found here. Copy of code and graph:

# Import library and dataset
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris')
 
# Cut the window in 2 parts
f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={"height_ratios": (.15, .85)})
 
# Add a graph in each part
sns.boxplot(df["sepal_length"], ax=ax_box)
sns.distplot(df["sepal_length"], ax=ax_hist)
 
# Remove x axis name for the boxplot
ax_box.set(xlabel='')

enter image description here

like image 44
Veliko Avatar answered Apr 27 '26 00:04

Veliko



Donate For Us

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