Python数据可视化-动态柱状图
·
目录
一、基础柱状图
1. 简单柱状图
from pyecharts.charts import Bar
from pyecharts import options as opts
# 创建柱状图对象
bar = Bar()
# 添加x轴数据(类别)
bar.add_xaxis(["苹果", "香蕉", "橙子", "葡萄", "西瓜"])
# 添加y轴数据(数值)
bar.add_yaxis("销量", [120, 150, 180, 90, 200])
# 设置全局配置
bar.set_global_opts(
title_opts=opts.TitleOpts(title="水果销量统计图", pos_left="center"),
xaxis_opts=opts.AxisOpts(name="水果名称"),
yaxis_opts=opts.AxisOpts(name="销量(kg)"),
tooltip_opts=opts.TooltipOpts(trigger="axis"),
)
# 生成HTML文件
bar.render("bar_basic.html")
print("✅ 基础柱状图已生成:bar_basic.html")
2. 多系列柱状图
from pyecharts.charts import Bar
from pyecharts import options as opts
bar = Bar()
bar.add_xaxis(["1月", "2月", "3月", "4月", "5月", "6月"])
# 添加多个系列
bar.add_yaxis("产品A", [100, 120, 150, 180, 200, 250])
bar.add_yaxis("产品B", [80, 90, 110, 130, 160, 190])
bar.add_yaxis("产品C", [60, 70, 85, 100, 120, 140])
bar.set_global_opts(
title_opts=opts.TitleOpts(title="月度产品销售对比", pos_left="center"),
xaxis_opts=opts.AxisOpts(name="月份"),
yaxis_opts=opts.AxisOpts(name="销售额(万元)"),
legend_opts=opts.LegendOpts(pos_left="70%"),
)
bar.render("bar_multi.html")
print("✅ 多系列柱状图已生成:bar_multi.html")
3. 反转x和y轴(水平柱状图)
from pyecharts.charts import Bar
from pyecharts import options as opts
bar = Bar()
bar.add_xaxis(["苹果", "香蕉", "橙子", "葡萄", "西瓜"])
bar.add_yaxis("销量", [120, 150, 180, 90, 200])
# 反转x轴和y轴(变成水平柱状图)
bar.reversal_axis()
# 设置数值标签在右侧显示
bar.set_series_opts(
label_opts=opts.LabelOpts(position="right") # 标签位置:right/left/top/bottom
)
bar.set_global_opts(
title_opts=opts.TitleOpts(title="水果销量统计图(水平)", pos_left="center"),
xaxis_opts=opts.AxisOpts(name="销量(kg)"),
yaxis_opts=opts.AxisOpts(name="水果名称"),
)
bar.render("bar_horizontal.html")
print("✅ 水平柱状图已生成:bar_horizontal.html")
二、基础时间线柱状图
1. 时间线基本使用
from pyecharts.charts import Bar, Timeline
from pyecharts import options as opts
# 创建时间线对象
timeline = Timeline()
# 准备多年份数据
years = ["2020年", "2021年", "2022年", "2023年"]
# 每年数据
data_2020 = [("苹果", 100), ("香蕉", 80), ("橙子", 60), ("葡萄", 90), ("西瓜", 70)]
data_2021 = [("苹果", 110), ("香蕉", 85), ("橙子", 65), ("葡萄", 95), ("西瓜", 75)]
data_2022 = [("苹果", 120), ("香蕉", 90), ("橙子", 70), ("葡萄", 100), ("西瓜", 80)]
data_2023 = [("苹果", 130), ("香蕉", 95), ("橙子", 75), ("葡萄", 105), ("西瓜", 85)]
# 为每年创建柱状图并添加到时间线
for year, data in zip(years, [data_2020, data_2021, data_2022, data_2023]):
bar = Bar()
# 按数值降序排序
data_sorted = sorted(data, key=lambda x: x[1], reverse=True)
x_data = [item[0] for item in data_sorted]
y_data = [item[1] for item in data_sorted]
bar.add_xaxis(x_data)
bar.add_yaxis("销量(kg)", y_data)
bar.reversal_axis()
bar.set_series_opts(label_opts=opts.LabelOpts(position="right"))
bar.set_global_opts(
title_opts=opts.TitleOpts(title=f"{year}水果销量", pos_left="center"),
xaxis_opts=opts.AxisOpts(name="销量(kg)"),
yaxis_opts=opts.AxisOpts(name="水果名称"),
)
timeline.add(bar, year)
# 时间线配置
timeline.add_schema(
play_interval=1000, # 自动播放间隔(毫秒)
is_auto_play=True, # 自动播放
is_loop_play=True, # 循环播放
is_timeline_show=True, # 显示时间线
)
timeline.render("timeline_basic.html")
print("✅ 基础时间线柱状图已生成:timeline_basic.html")
2. 带主题的时间线
from pyecharts.charts import Bar, Timeline
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# 创建时间线并设置主题
timeline = Timeline({"theme": ThemeType.LIGHT}) # 可选:LIGHT, DARK, CHALK, PURPLE, WALDEN, WESTEROS, SHINE, MACARONS
# 准备数据
years = ["2020", "2021", "2022", "2023"]
data_by_year = {
"2020": [("中国", 100), ("美国", 95), ("日本", 80), ("德国", 75), ("英国", 70)],
"2021": [("中国", 110), ("美国", 100), ("日本", 85), ("德国", 80), ("英国", 75)],
"2022": [("中国", 120), ("美国", 105), ("日本", 90), ("德国", 85), ("英国", 80)],
"2023": [("中国", 130), ("美国", 110), ("日本", 95), ("德国", 90), ("英国", 85)],
}
for year in years:
bar = Bar()
data = data_by_year[year]
data_sorted = sorted(data, key=lambda x: x[1], reverse=True)
bar.add_xaxis([item[0] for item in data_sorted])
bar.add_yaxis("GDP(百亿)", [item[1] for item in data_sorted])
bar.reversal_axis()
bar.set_series_opts(label_opts=opts.LabelOpts(position="right"))
bar.set_global_opts(
title_opts=opts.TitleOpts(title=f"{year}年全球GDP前5名", pos_left="center"),
xaxis_opts=opts.AxisOpts(name="GDP(百亿美元)"),
yaxis_opts=opts.AxisOpts(name="国家"),
)
timeline.add(bar, year)
timeline.add_schema(
play_interval=1000,
is_auto_play=True,
is_loop_play=True,
is_timeline_show=True,
)
timeline.render("timeline_theme.html")
print("✅ 带主题的时间线柱状图已生成:timeline_theme.html")
三、列表排序补充
1. sort() 与 sorted() 的区别
# sorted():返回新列表,原列表不变
print("=== sorted() 函数 ===")
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(f"原列表:{numbers}") # [3, 1, 4, 1, 5, 9, 2]
print(f"排序后:{sorted_numbers}") # [1, 1, 2, 3, 4, 5, 9]
# sort():直接修改原列表,返回None
print("\n=== sort() 方法 ===")
numbers = [3, 1, 4, 1, 5, 9, 2]
result = numbers.sort()
print(f"sort返回值:{result}") # None
print(f"原列表:{numbers}") # [1, 1, 2, 3, 4, 5, 9]
2. 使用key参数排序
print("=== 带key参数的排序 ===")
# 对字典列表按指定字段排序
students = [
{"name": "张三", "score": 85},
{"name": "李四", "score": 92},
{"name": "王五", "score": 78},
{"name": "赵六", "score": 88},
]
# 按分数升序
students.sort(key=lambda x: x["score"])
print("按分数升序:")
for s in students:
print(f" {s['name']}: {s['score']}")
# 按分数降序
students.sort(key=lambda x: x["score"], reverse=True)
print("\n按分数降序:")
for s in students:
print(f" {s['name']}: {s['score']}")
输出:
=== 带key参数的排序 === 按分数升序: 王五: 78 张三: 85 赵六: 88 李四: 92 按分数降序: 李四: 92 赵六: 88 张三: 85 王五: 78
3. 元组列表排序
print("=== 元组列表排序 ===")
# 数据格式:[(国家, GDP), ...]
gdp_data = [
("美国", 21000), ("中国", 15000), ("日本", 5000),
("德国", 4000), ("英国", 3000), ("印度", 2800),
("法国", 2700), ("意大利", 2000), ("巴西", 1800),
]
# 按GDP降序排序(取前5)
gdp_data.sort(key=lambda x: x[1], reverse=True)
top5 = gdp_data[:5]
print("GDP前5名:")
for country, gdp in top5:
print(f" {country}: {gdp}亿美元")
输出:
=== 元组列表排序 === GDP前5名: 美国: 21000亿美元 中国: 15000亿美元 日本: 5000亿美元 德国: 4000亿美元 英国: 3000亿美元
四、GDP动态柱状图绘制(完整案例)
1. 数据处理
import json
# 模拟GDP数据(实际从JSON文件读取)
# 格式:{年份: [(国家, GDP), ...]}
gdp_data = {
1960: [("美国", 5433), ("苏联", 4123), ("英国", 732), ("法国", 622), ("德国", 724)],
1970: [("美国", 10725), ("苏联", 5634), ("日本", 2120), ("德国", 2150), ("英国", 1306)],
1980: [("美国", 28564), ("日本", 11133), ("苏联", 9400), ("德国", 8500), ("英国", 5630)],
1990: [("美国", 59631), ("日本", 31372), ("德国", 17636), ("英国", 11214), ("法国", 12687)],
2000: [("美国", 102523), ("日本", 47671), ("德国", 19456), ("英国", 16482), ("法国", 13617)],
2010: [("美国", 149920), ("中国", 60872), ("日本", 57010), ("德国", 34170), ("英国", 24780)],
2019: [("美国", 214332), ("中国", 143429), ("日本", 50818), ("德国", 38611), ("英国", 28316)],
}
print("=== 数据处理 ===")
print(f"共 {len(gdp_data)} 年数据")
# 查看某一年数据
print(f"\n2019年GDP数据(原始):")
for country, gdp in gdp_data[2019]:
print(f" {country}: {gdp}亿美元")
# 转换为亿为单位(如果原始数据是亿,这里不需要除以10000)
# 假设原始数据已经是亿美元,直接使用
print("\n数据已准备完成")
2. 创建动态GDP柱状图
from pyecharts.charts import Bar, Timeline
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# GDP数据(单位:亿美元)
gdp_data = {
1960: [("美国", 5433), ("苏联", 4123), ("英国", 732), ("法国", 622), ("德国", 724), ("日本", 443), ("中国", 597)],
1970: [("美国", 10725), ("苏联", 5634), ("日本", 2120), ("德国", 2150), ("英国", 1306), ("法国", 1470), ("中国", 926)],
1980: [("美国", 28564), ("日本", 11133), ("苏联", 9400), ("德国", 8500), ("英国", 5630), ("法国", 6960), ("中国", 1911)],
1990: [("美国", 59631), ("日本", 31372), ("德国", 17636), ("英国", 11214), ("法国", 12687), ("意大利", 11360), ("中国", 3614)],
2000: [("美国", 102523), ("日本", 47671), ("德国", 19456), ("英国", 16482), ("法国", 13617), ("中国", 12100), ("意大利", 11068)],
2010: [("美国", 149920), ("中国", 60872), ("日本", 57010), ("德国", 34170), ("英国", 24780), ("法国", 26480), ("印度", 16700)],
2019: [("美国", 214332), ("中国", 143429), ("日本", 50818), ("德国", 38611), ("英国", 28316), ("印度", 28700), ("法国", 27100)],
}
print("=== 创建动态GDP柱状图 ===")
# 创建时间线对象(设置主题)
timeline = Timeline({"theme": ThemeType.LIGHT})
# 按年份排序
years = sorted(gdp_data.keys())
for year in years:
# 获取该年数据
data = gdp_data[year]
# 按GDP降序排序,取前8名
data_sorted = sorted(data, key=lambda x: x[1], reverse=True)[:8]
# 提取国家名和GDP
countries = [item[0] for item in data_sorted]
gdps = [round(item[1]) for item in data_sorted] # 取整
print(f"处理{year}年数据,前{len(countries)}名:{countries[:3]}...")
# 创建柱状图
bar = Bar()
# 添加数据
bar.add_xaxis(countries)
bar.add_yaxis("GDP(亿美元)", gdps)
# 反转x和y轴(变成水平柱状图)
bar.reversal_axis()
# 设置数值标签在右侧显示
bar.set_series_opts(
label_opts=opts.LabelOpts(
position="right",
formatter="{c} 亿美元"
)
)
# 设置全局配置
bar.set_global_opts(
title_opts=opts.TitleOpts(
title=f"{year}年全球GDP前8名",
subtitle="单位:亿美元",
pos_left="center",
title_textstyle_opts=opts.TextStyleOpts(font_size=18)
),
xaxis_opts=opts.AxisOpts(
name="GDP",
name_location="middle",
name_gap=30,
axislabel_opts=opts.LabelOpts(formatter="{value} 亿")
),
yaxis_opts=opts.AxisOpts(
name="国家",
name_location="middle",
name_gap=40,
axislabel_opts=opts.LabelOpts(font_size=12)
),
tooltip_opts=opts.TooltipOpts(
trigger="axis",
axis_pointer_type="shadow",
formatter="{b}<br/>GDP: {c} 亿美元"
),
legend_opts=opts.LegendOpts(is_show=False),
)
# 添加到时间线
timeline.add(bar, str(year))
# 时间线配置
timeline.add_schema(
play_interval=800, # 播放间隔(毫秒)
is_auto_play=True, # 自动播放
is_loop_play=True, # 循环播放
is_timeline_show=True, # 显示时间线
orient="horizontal", # 水平方向
label_opts=opts.LabelOpts(rotate=0)
)
# 生成HTML文件
timeline.render("gdp_timeline.html")
print("\n✅ 动态GDP柱状图已生成:gdp_timeline.html")
print("请在浏览器中打开文件,查看1960-2019年GDP动态变化")
3. 带颜色渐变的动态柱状图
from pyecharts.charts import Bar, Timeline
from pyecharts import options as opts
from pyecharts.globals import ThemeType
gdp_data = {
1960: [("美国", 5433), ("苏联", 4123), ("德国", 724), ("英国", 732), ("法国", 622), ("日本", 443), ("中国", 597)],
1980: [("美国", 28564), ("日本", 11133), ("苏联", 9400), ("德国", 8500), ("法国", 6960), ("英国", 5630), ("中国", 1911)],
2000: [("美国", 102523), ("日本", 47671), ("德国", 19456), ("英国", 16482), ("法国", 13617), ("中国", 12100), ("意大利", 11068)],
2019: [("美国", 214332), ("中国", 143429), ("日本", 50818), ("德国", 38611), ("英国", 28316), ("印度", 28700), ("法国", 27100)],
}
# 主题列表
themes = {
1960: ThemeType.CHALK,
1980: ThemeType.PURPLE,
2000: ThemeType.MACARONS,
2019: ThemeType.WESTEROS,
}
timeline = Timeline()
for year, data in gdp_data.items():
data_sorted = sorted(data, key=lambda x: x[1], reverse=True)[:7]
countries = [item[0] for item in data_sorted]
gdps = [item[1] for item in data_sorted]
bar = Bar({"theme": themes.get(year, ThemeType.LIGHT)})
bar.add_xaxis(countries)
bar.add_yaxis(
"GDP(亿美元)",
gdps,
itemstyle_opts=opts.ItemStyleOpts(
borderRadius=[0, 10, 10, 0], # 圆角
shadow_color="rgba(0,0,0,0.3)",
shadow_blur=10
)
)
bar.reversal_axis()
bar.set_series_opts(
label_opts=opts.LabelOpts(
position="right",
formatter="{c} 亿",
font_size=12
)
)
# 添加视觉映射(颜色渐变)
bar.set_global_opts(
title_opts=opts.TitleOpts(
title=f"{year}年全球GDP排名",
pos_left="center",
title_textstyle_opts=opts.TextStyleOpts(font_size=20)
),
xaxis_opts=opts.AxisOpts(name="GDP(亿美元)"),
yaxis_opts=opts.AxisOpts(name="国家"),
visualmap_opts=opts.VisualMapOpts(
is_show=False,
min_=min(gdps),
max_=max(gdps),
range_color=["#50a3ba", "#eac736", "#d94e5d"]
),
)
timeline.add(bar, str(year))
timeline.add_schema(
play_interval=1500,
is_auto_play=True,
is_loop_play=False,
is_timeline_show=True,
)
timeline.render("gdp_timeline_style.html")
print("✅ 带样式的动态GDP柱状图已生成:gdp_timeline_style.html")
五、主题类型参考
from pyecharts.globals import ThemeType
# 可用主题列表
themes = [
ThemeType.LIGHT, # 亮色主题(默认)
ThemeType.DARK, # 暗色主题
ThemeType.CHALK, # 粉笔风格
ThemeType.PURPLE, # 紫色风格
ThemeType.WALDEN, # 瓦尔登湖风格
ThemeType.WESTEROS, # 维斯特洛风格
ThemeType.SHINE, # 闪亮风格
ThemeType.MACARONS, # 马卡龙风格
ThemeType.ROMANTIC, # 浪漫风格
]
# 使用方式
# bar = Bar({"theme": ThemeType.DARK})
# timeline = Timeline({"theme": ThemeType.CHALK})
六、时间线配置速查
| 参数 | 说明 | 示例 |
|---|---|---|
play_interval |
自动播放间隔(毫秒) | play_interval=1000 |
is_auto_play |
是否自动播放 | is_auto_play=True |
is_loop_play |
是否循环播放 | is_loop_play=True |
is_timeline_show |
是否显示时间线控件 | is_timeline_show=True |
orient |
方向(horizontal/vertical) | orient="horizontal" |
七、完整代码总结
# 导入模块
from pyecharts.charts import Bar, Timeline
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# 1. 基础柱状图
bar = Bar()
bar.add_xaxis(["A", "B", "C"])
bar.add_yaxis("数值", [10, 20, 30])
bar.render("bar.html")
# 2. 水平柱状图(反转x/y轴)
bar.reversal_axis()
bar.set_series_opts(label_opts=opts.LabelOpts(position="right"))
# 3. 时间线动态图
timeline = Timeline({"theme": ThemeType.LIGHT})
for year in years:
bar = Bar()
# ... 添加数据
timeline.add(bar, str(year))
timeline.add_schema(play_interval=1000, is_auto_play=True)
timeline.render("timeline.html")
# 4. 列表排序(用于数据处理)
data.sort(key=lambda x: x[1], reverse=True) # 降序
data.sort(key=lambda x: x[1]) # 升序
top_n = data[:8] # 取前8名更多推荐
所有评论(0)