如何基于带时间戳的日期与行业数据绘制每月最高频行业图表?
实现方案(Python为例)
1. 数据预处理
- 首先将原始时间戳字段转换为可识别的日期格式,提取年-月维度作为聚合键
- 清理行业字段的空值、异常值,确保同一行业命名统一(比如避免“电商”和“电子商务”同时出现的统计误差)
2. 按月份+行业聚合统计频次
用pandas实现的示例代码如下:
import pandas as pd # 假设你的原始数据存为DataFrame对象df,包含两个核心字段:timestamp(时间戳)、industry(行业名称) # 转换时间戳为月份字段,unit参数根据你实际时间戳的单位调整(秒级用's',毫秒级用'ms') df['month'] = pd.to_datetime(df['timestamp'], unit='s').dt.to_period('M') # 按月份+行业分组统计出现频次 month_industry_counts = df.groupby(['month', 'industry']).size().reset_index(name='count') # 筛选每个月频次最高的行业 # 写法1:保留所有并列最高的行业 month_top_industry = month_industry_counts.loc[month_industry_counts.groupby('month')['count'].idxmax()] # 写法2:如果每个月只保留1个最高值,可加排序后去重 # month_industry_counts = month_industry_counts.sort_values(['month', 'count'], ascending=[True, False]) # month_top_industry = month_industry_counts.drop_duplicates('month', keep='first')
3. 可视化绘制
根据你的展示需求可选两种常用图表形式:
3.1 频次柱状图(同时展示最高行业名称+对应频次数值)
import matplotlib.pyplot as plt # 把月份转为字符串避免绘图格式异常 month_top_industry['month'] = month_top_industry['month'].astype(str) # 给不同行业分配固定颜色,方便快速识别 color_map = {industry: plt.cm.tab10(i) for i, industry in enumerate(month_top_industry['industry'].unique())} colors = month_top_industry['industry'].map(color_map) plt.figure(figsize=(12, 6)) bars = plt.bar(month_top_industry['month'], month_top_industry['count'], color=colors) # 每个柱子上标注对应行业名称 for bar, industry in zip(bars, month_top_industry['industry']): plt.text(bar.get_x() + bar.get_width()/2, bar.get_height(), industry, ha='center', va='bottom', fontsize=9) plt.xlabel('月份') plt.ylabel('最高行业出现频次') plt.title('各月出现频次最高行业分布') plt.xticks(rotation=45) plt.tight_layout() plt.show()
3.2 趋势热力图(仅展示各月最高行业的变化规律)
# 把数据转为透视表格式 pivot_df = month_top_industry.pivot_table(index='industry', columns='month', values='count', aggfunc='max').fillna(0) # 转为布尔值更适合热力图展示 pivot_df = pivot_df > 0 plt.figure(figsize=(12, 8)) plt.imshow(pivot_df, aspect='auto', cmap='Blues', interpolation='nearest') plt.yticks(range(len(pivot_df.index)), pivot_df.index) plt.xticks(range(len(pivot_df.columns)), pivot_df.columns, rotation=45) plt.xlabel('月份') plt.ylabel('行业') plt.title('各月频次最高行业变化趋势') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Omar
相关产品推荐
相关产品推荐

