如何使用Matplotlib限制Seaborn countplot中显示的组数?
为了限制Seaborn countplot中显示的组数,我们可以使用变量 group_count ,用于 countplot() 方法的参数中。
步骤
- 创建一个图形和两组子图。
-
使用Pandas创建一个具有两个键的数据帧。
-
初始化一个变量 group_count 以限制 countplot() 方法中的组数。
-
使用 countplot() 方法以杆形图显示每个分类区间中观察值的计数。
-
调整子图之间和周围的间距。
示例
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
f, axes = plt.subplots(1, 2)
df = pd.DataFrame(dict(col1=np.linspace(1, 10, 5), col2=np.linspace(1, 10, 5), col3=np.linspace(1, 10, 5)))
group_count = 1
sns.countplot(df.col1, x='col1', color="red", ax=axes[0], order=df.col1.value_counts().iloc[:group_count].index)
sns.countplot(df.col2, x="col2", color="green", ax=axes[1], order=df.col2.value_counts().iloc[:group_count].index)
plt.tight_layout()
plt.show()