f,[ax1,ax2,ax3]=plt.subplots(1,3,figsize=(20,5)) sns.countplot(x='BusinessTravel',hue='Attrition',data=train_data,ax=ax1) sns.countplot(x='Department',hue='Attrition',data=train_data,ax=ax2) sns.countplot(x='Gender',hue='Attrition',data=train_data,ax=ax3) ax1.set_title('Business特征分析') ax2.set_title('Depeartment特征分析') ax3.set_title('Gender特征分析') f.suptitle('定类数据类型特征分析',size=20,y=1.1) f,[ax1,ax2]=plt.subplots(1,2,figsize=(20,5)) sns.countplot(x='MaritalStatus',hue='Attrition',data=train_data,ax=ax1) sns.countplot(x='OverTime',hue='Attrition',data=train_data,ax=ax2) ax1.set_title('MaritalStatus特征分析') ax2.set_title('OverTime特征分析') plt.show()
时间: 2023-06-26 14:03:41 浏览: 158
这段代码使用了matplotlib和seaborn库来绘制多个计数图,用于分析定类数据类型特征在Attrition(离职)中的分布情况。首先通过plt.subplots()方法创建一个1行3列的子图和一个大小为20x5的figure对象,然后分别使用sns.countplot()方法和不同的子图对象ax1、ax2、ax3来绘制三个特征的计数图,并设置图表标题和主标题。接下来再创建一个1行2列的子图和另一个大小为20x5的figure对象,绘制两个其他特征的计数图,并设置标题。最后使用plt.show()方法显示图表。
相关问题
# 创建图像 grid_kws = {"width_ratios": (.9, .9, .05), "wspace": 0.2} f, (ax1, ax2, cbar_ax) = plt.subplots(1, 3, gridspec_kw=grid_kws, figsize = (18, 9)) # 定义调色板 cmap = sns.diverging_palette(0, 230, 90, 60, as_cmap=True) # 画 NotFraud 表中的各个特征间相关性热力图 # 计算上三角mask矩阵 mask1 = np.zeros_like(corr_NotFraud) indices = np.triu_indices_from(corr_NotFraud) mask1[indices] = True # 过滤空值 mask1 = mask1[1:, :-1] corr_NotFraud = corr_NotFraud.iloc[1:, :-1].copy() ax1 =sns.???(corr_NotFraud, ax = ax1, vmin = -1, vmax = 1, cmap = cmap, square = False, \ annot=True, fmt=".2f", linewidths = 0.5, mask = mask1, cbar = False) ax1.set_xticklabels(ax1.get_xticklabels(), size = 16); ax1.set_yticklabels(ax1.get_yticklabels(), size = 16); ax1.set_title('fraud=1的热力图', size = 20)
这段代码中缺少 `heatmap` 方法名,应该是 `sns.heatmap`。因此,你可以使用以下代码画 NotFraud 表中的各个特征间相关性热力图:
```
ax1 = sns.heatmap(corr_NotFraud, ax=ax1, vmin=-1, vmax=1, cmap=cmap, square=False, annot=True, fmt=".2f", linewidths=0.5, mask=mask1, cbar=False)
```
其中,`corr_NotFraud` 是相关系数矩阵,`ax=ax1` 表示将热力图绘制在 `ax1` 坐标轴上,`vmin` 和 `vmax` 分别表示颜色映射的最小值和最大值,`cmap` 表示使用的颜色映射,`square=False` 表示关闭正方形显示模式,`annot=True` 表示在每个格子内显示数值,`fmt=".2f"` 表示显示的数值的格式,`linewidths=0.5` 表示格子之间的线宽度,`mask=mask1` 表示过滤空值,`cbar=False` 表示关闭颜色条。
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'Fangsong' # 指定使用宋体字体 fig=plt.figure(figsize=(40,50), dpi=300) ax1=fig.add_subplot(131) ax2=fig.add_subplot(132) ax3=fig.add_subplot(133) # 读取数据 df = pd.read_excel("test_Fd.xlsx") # 按照 FactoryName 和 JiJXH 进行分组,计算售价最高值和最低值 grouped = df.groupby("FenDMC")['avg_sale'].agg(['min', 'max']).reset_index() grouped = grouped.rename(columns={'min': 'min_sale', 'max': 'max_sale'}) # 将售价最高值和最低值合并到原表中 df = pd.merge(df, grouped, on=["FenDMC"]) # 绘制热力图,并设置颜色取值范围 sns.set_context(font_scale=1.5) sns.heatmap(df.pivot_table(index=["FactoryName","JiJXH"], columns=["shi"], values="avg_sale"), cmap='YlGnBu', annot=True, fmt='.2f', cbar_kws={'label': '单台售价','shrink':0.8,'aspect':40}, vmin=grouped['min_sale'].min(), vmax=grouped['max_sale'].max()) plt.xlabel(None) plt.ylabel(None) plt.title('''200马力及以上四轮驱动拖拉机 各生产企业各型号在不同市单台平均售价''', fontsize=20) # 调整边距,使图像居中 plt.tight_layout() # 保存图像 plt.savefig('heatmap.png') plt.show()如何把不同FenDMC,按照FactoryName,jiJXH按照avg_sale绘制到不同子图
可以使用 Pandas 的 `groupby` 方法按照 `FenDMC` 进行分组,并遍历每个分组,将每个分组的数据绘制到不同的子图中。示例代码如下:
```python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Fangsong' # 指定使用宋体字体
fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(30, 25), dpi=300) # 创建 9 个子图
# 读取数据
df = pd.read_excel("test_Fd.xlsx")
# 按照 FenDMC 进行分组
groups = df.groupby("FenDMC")
# 遍历每个分组,绘制子图
for idx, (name, group) in enumerate(groups):
# 按照 FactoryName 和 JiJXH 进行分组,计算平均售价
grouped = group.groupby(["FactoryName", "JiJXH"])['avg_sale'].mean().reset_index()
# 在对应的子图中绘制热力图
row = idx // 3
col = idx % 3
ax = axes[row, col]
sns.heatmap(grouped.pivot_table(index="FactoryName", columns="JiJXH", values="avg_sale"),
cmap='YlGnBu', annot=True, fmt='.2f',
cbar_kws={'label': '单台售价', 'shrink':0.8, 'aspect':40},
ax=ax)
ax.set_xlabel(None)
ax.set_ylabel(None)
ax.set_title(name, fontsize=20)
# 调整边距,使图像居中
plt.tight_layout()
# 保存图像
plt.savefig('heatmap.png')
# 显示图像
plt.show()
```
这样就可以将不同的 `FenDMC` 分别绘制到不同的子图中,每个子图中按照 `FactoryName` 和 `JiJXH` 绘制热力图,并显示对应的标题。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)