Ran*_*dy 3 python loops matplotlib seaborn
我正在尝试创建一个子图网格。每个子图看起来都像这个网站上的子图。
https://python-graph-gallery.com/24-histogram-with-a-boxplot-on-top-seaborn/
例如,如果我有 10 组不同的这种风格的绘图,我想将它们制作成 5x2。
我已阅读 Matplotlib 的文档,但似乎无法弄清楚如何做到这一点。我可以循环子图并获得每个输出,但我无法将其放入行和列中
导入pandas作为pd 导入numpy作为np 导入seaborn作为sns
df = pd.DataFrame(np.random.randint(0,100,size=(100, 10)),columns=list('ABCDEFGHIJ'))
for c in df :
# Cut the window in 2 parts
f, (ax_box,
ax_hist) = plt.subplots(2,
sharex=True,
gridspec_kw={"height_ratios":(.15, .85)},
figsize = (10, 10))
# Add a graph in each part
sns.boxplot(df[c], ax=ax_box)
ax_hist.hist(df[c])
# Remove x axis name for the boxplot
plt.show()
Run Code Online (Sandbox Code Playgroud)
结果只是采用这个循环并将它们放入一组行和列中,在本例中为 5x2
您有 10 列,每列创建 2 个子图:箱形图和直方图。所以你总共需要 20 个数字。您可以通过创建 2 行 10 列的网格来完成此操作
完整答案:(根据口味调整figsize
和)height_ratios
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
f, axes = plt.subplots(2, 10, sharex=True, gridspec_kw={"height_ratios":(.35, .35)},
figsize = (12, 5))
df = pd.DataFrame(np.random.randint(0,100,size=(100, 10)),columns=list('ABCDEFGHIJ'))
for i, c in enumerate(df):
sns.boxplot(df[c], ax=axes[0,i])
axes[1,i].hist(df[c])
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2713 次 |
最近记录: |