Python Bokeh 可视化:不同职业中的婚姻状态占比分析
使用 Python Bokeh 可视化不同职业中的婚姻状态占比分析
本示例使用 Python 的 Bokeh 库,对不同职业中的婚姻状态占比进行可视化分析。通过直观的图表展现数据,分析婚姻状态与职业之间的关系。
代码实现
from bokeh.plotting import figure, show, output_file
import numpy as np
import pandas as pd
import pandas
df = pd.read_csv(r'/Users/fuchuanruo/Desktop/可视化作业/实践/train.csv')
test = pd.read_csv(r'/Users/fuchuanruo/Desktop/可视化作业/实践/test.csv')
# 数据处理
marital_counts = df.groupby(['marital', 'job']).size().unstack()
marital_counts = marital_counts.div(marital_counts.sum(axis=1), axis=0)
# 可视化分析
output_file('marital_job.html')
jobs = list(marital_counts.columns)
marital_statuses = list(marital_counts.index)
colors = ['#c9d9d3', '#718dbf', '#e84d60', '#ddb7b1', '#bcbd22', '#565656', '#11a579', '#7f3c8d', '#f15b2a', '#ce6dbd', '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
mapper = LinearColorMapper(palette=colors, low=0, high=1)
p = figure(title='Marital Status vs Job', x_range=jobs, y_range=list(reversed(marital_statuses)),
plot_width=800, plot_height=600, toolbar_location=None, tools='')
p.rect(x=[job for job in jobs for marital in marital_statuses],
y=[marital for job in jobs for marital in marital_statuses],
width=1, height=1, fill_color={'field': '@value', 'transform': mapper},
source=ColumnDataSource(data={'value': [marital_counts.loc[marital, job] for job in jobs for marital in marital_statuses]}))
color_bar = ColorBar(color_mapper=mapper, location=(0, 0))
p.add_layout(color_bar, 'right')
p.xaxis.major_label_orientation = np.pi/4
p.xaxis.axis_label = 'Job'
p.yaxis.axis_label = 'Marital Status'
show(p)
代码解释
- 数据处理: 使用
pandas库对数据进行处理,计算每个职业中不同婚姻状态的占比。 - 可视化: 使用
bokeh库创建直方图,展示不同职业中不同婚姻状态的占比。- 使用
LinearColorMapper设置颜色映射,将占比值映射到不同的颜色。 - 使用
rect函数绘制矩形,矩形的颜色根据占比值进行映射。 - 使用
ColorBar展示颜色映射的对应值。
- 使用
- 图表设置: 设置图表的标题、坐标轴标签、尺寸等。
结论
通过可视化图表,可以直观地观察不同职业中不同婚姻状态的占比情况,并分析婚姻状态与职业之间的关系。
注意: 该示例需要安装 bokeh 和 pandas 库。
pip install bokeh pandas
示例数据: 需要提供示例数据,才能运行该示例。
希望这个示例能帮助你理解如何使用 bokeh 库进行数据可视化分析。
原文地址: https://www.cveoy.top/t/topic/jjXW 著作权归作者所有。请勿转载和采集!