# python绘图中的 四个绘图技巧

```import seaborn as sns # v0.11.2
import matplotlib.pyplot as plt # v3.4.2

```

## 技巧1: plt.subplots()

```fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10,4))
sns.histplot(data=df, x="tip", ax=ax[0])
sns.boxplot(data=df, x="tip", ax=ax[1]);

```

例如，我们可以像这样为每个子图添加标题：

```fig, ax = plt.subplots(1, 2, figsize=(10,4))
sns.histplot(data=df, x="tip", ax=ax[0])
ax[0].set\_title("Histogram")
sns.boxplot(data=df, x="tip", ax=ax[1])
ax[1].set\_title("Boxplot");

```

```numerical = df.select\_dtypes("number").columnsfor col in numerical:
fig, ax = plt.subplots(1, 2, figsize=(10,4))
sns.histplot(data=df, x=col, ax=ax[0])
sns.boxplot(data=df, x=col, ax=ax[1]);

```

## 技巧2: plt.subplot()

语法与之前略有不同：

```plt.figure(figsize=(10,4))
ax1 = plt.subplot(1,2,1)
sns.histplot(data=df, x="tip", ax=ax1)
ax2 = plt.subplot(1,2,2)
sns.boxplot(data=df, x="tip", ax=ax2);

```

```plt.figure(figsize=(14,4))
for i, col in enumerate(numerical):
ax = plt.subplot(1, len(numerical), i+1)
sns.boxplot(data=df, x=col, ax=ax)

```

```plt.figure(figsize=(14,4))
for i, col in enumerate(numerical):
ax = plt.subplot(1, len(numerical), i+1)
sns.boxplot(data=df, x=col, ax=ax)
ax.set\_title(f"Boxplot of {col}")

```

## 技巧3: plt.tight_layout()

```categorical = df.select\_dtypes("category").columnsplt.figure(figsize=(8, 8))
for i, col in enumerate(categorical):
ax = plt.subplot(2, 2, i+1)
sns.countplot(data=df, x=col, ax=ax)

```

```plt.figure(figsize=(8, 8))
for i, col in enumerate(categorical):
ax = plt.subplot(2, 2, i+1)
sns.countplot(data=df, x=col, ax=ax)
plt.tight\_layout()

```

## 技巧4: plt.suptitle()

```plt.figure(figsize=(8, 8))
for i, col in enumerate(categorical):
ax = plt.subplot(2, 2, i+1)
sns.countplot(data=df, x=col, ax=ax)
plt.suptitle("Category counts for all categorical variables")
plt.tight\_layout()

```