Python Bokeh库可视化分析:婚姻状况与职业分布关系

本案例使用 Python 的 Bokeh 库对数据集中的婚姻状况与职业类别进行可视化分析,探索两者之间的关系。

数据预处理

  1. 从CSV文件读取数据
  2. 提取 'marital' 和 'job' 列
  3. 清理缺失值
  4. 按 'marital' 和 'job' 分组统计数量
import pandas as pd
from bokeh.plotting import figure, show, output_file
from bokeh.palettes import Category20
from bokeh.transform import factor_cmap

df = pd.read_csv('train.csv')
df = df[['marital', 'job']]
df = df.dropna()
df = df.groupby(['marital', 'job']).size().reset_index(name='counts')

数据可视化

  1. 使用 Bokeh 创建柱状图
  2. 设置图表标题、尺寸、坐标轴标签等
  3. 使用不同颜色区分不同的职业类别
  4. 添加图例
output_file('marital_job.html')

p = figure(plot_width=800, plot_height=400, title='婚姻状况与职业分布关系',
           x_range=df.marital.unique(), toolbar_location=None, tools='')

p.vbar(x='marital', top='counts', width=0.9, source=df,
       line_color='white', fill_color=factor_cmap('job', palette=Category20[20], factors=df.job.unique()))

p.xgrid.grid_line_color = None
p.y_range.start = 0
p.y_range.end = 2000
p.legend.orientation = 'horizontal'
p.legend.location = 'top_center'

show(p)

结果展示

最终生成的HTML文件将展示一个交互式柱状图,清晰地展示不同婚姻状况在各职业中的占比情况,便于用户进行数据分析和洞察。

Python Bokeh库可视化分析:婚姻状况与职业分布关系

原文地址: https://www.cveoy.top/t/topic/jjXJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录