惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
云风的 BLOG
云风的 BLOG
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
AWS News Blog
AWS News Blog
S
SegmentFault 最新的问题
T
Tailwind CSS Blog
The Hacker News
The Hacker News
GbyAI
GbyAI
P
Palo Alto Networks Blog
博客园 - 三生石上(FineUI控件)
Y
Y Combinator Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - Franky
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Cyberwarzone
Cyberwarzone
H
Help Net Security
S
Securelist
月光博客
月光博客
博客园 - 【当耐特】
T
Threatpost
T
Tenable Blog
G
GRAHAM CLULEY
博客园 - 司徒正美
I
Intezer
MyScale Blog
MyScale Blog
T
Threat Research - Cisco Blogs
P
Privacy & Cybersecurity Law Blog
The GitHub Blog
The GitHub Blog
C
CERT Recently Published Vulnerability Notes
T
Tor Project blog
Google DeepMind News
Google DeepMind News
C
Cybersecurity and Infrastructure Security Agency CISA
罗磊的独立博客
腾讯CDC
P
Privacy International News Feed
博客园_首页
The Cloudflare Blog
Cisco Talos Blog
Cisco Talos Blog
A
About on SuperTechFans
V
Vulnerabilities – Threatpost
A
Arctic Wolf
B
Blog RSS Feed
Recorded Future
Recorded Future
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
S
Security Affairs
Microsoft Security Blog
Microsoft Security Blog
L
LangChain Blog

又见苍岚

COLMAP PatchMatch Stereo 算法详解 事件驱动的状态机框架:从理论到工程实践 Git 在国内网络环境下无法 Push 的排查与修复 —— 配置 Clash 代理 分段五次多项式插值原理详解 路径插值方法深度对比研究 Claude Code 使用指南 OpenClaw 记忆管理与技能创建指南 CBS(Conflict-Based Search)算法详解 A* 算法及其变种详解 OpenClaw 配置多 Agents Windows Powershell 无法加载文件,因为在此系统上禁止运行脚本问题的解决方案 MaxClaw 安装流程 大模型 AI 名词介绍 AList 网盘聚合工具简介 Protobuf 简介与测试 Claude Code 简介以及 GLM 4.7 模型接入 Github 歌词下载工具 163MusicLyrics Python __getattr__ 懒加载 Python TypedDict 机器人仿真平台 Gazebo 安装记录 机器人仿真平台 Gazebo 简介 多机器人路径规划问题(Multi-Agent Path Finding, MAPF)简介 Python exifread 读取修改过的 jpeg 信息错误问题修复 3D 坐标系变换的理解 3D 旋转矩阵基本概念 MongoDB Compass 介绍 Python 环境管理工具 uv Flutter 开发指南 Snipaste 安装下载与黑屏问题解决方案 全局路径规划算法记录 2025 Python 版本性能测试 Flutter Hello World Flutter 安装环境配置 Ubuntu VMware 硬盘扩容后 SMBus Host controller not enabled 报错问题解决 Python NetworkX 教程 Docker GPU 报错 - Failed to initialize NVML Unknown Error 解决方案 cuda-toolkit 安装替代 Cuda 与 Cudnn Jinja2 Python 利用 docxtpl 和 Jinja2 生成基于模板的 Word 文档 Docker 实现 CPU 核心隔离 LoFTR 基于 Transformer 的特征提取匹配算法 OmniGlue 特征匹配 SuperGlue 使用图神经网络学习特征匹配 Ubuntu 下将 xlsx 文件按照 sheet 转换为 图片 Python 使用 SQLAlchemy Python FastAPI 教程 openwrt 软路由配置安装 Nav2 地图文件(PGM/YAML)规范标准 3D OBJ 模型转换为 glb 瓦片格式 Python 源码 Redis 数据库介绍 Ubuntu 22.04 内核自动升级导致 MongoDB 7.0.12 错误记录 ubuntu 20.04 安装 ROS Noetic ubuntu 18.04 安装 ROS Melodic VMware Workstation Pro 个人免费版下载、安装、使用指南 Hybrid A-star 路径规划 Reeds-Shepp 曲线 Dubins 曲线 Linux kvm 虚拟机网络不通的问题解决方法 Ubuntu 自动内存清理 BiliBili 缓存视频转 mp4 Python 求解线性规划 3D Gaussian Splatting 官方源码实践记录 ImageMagick 教程 Ubuntu 22.04 安装 Colmap 对数几率 odds Ubuntu nmcli 网络管理工具使用指南 SuperPoint 自监督深度学习特征点提取 SyncTV Music Tag Web 在线音乐信息整理工具 ncm 格式转 mp3 MusicBrainz 音乐元数据百科数据库 Ubuntu 网络流量监控工具 私人云音乐平台 Navidrome 入门 手眼标定 四元数(Quaternions) OHTTPS 实现免费自动 https 证书申请、更新、部署 ubuntu 22.04 安装 CloudCompare 单机 KVM 虚拟机冷迁移 Ubuntu 22.04 使用 mdadm 实现软 raid 小鱼 一键安装 ROS-humble Fluid -46- 基于 Simpletex API 构建公式识别页面 公式识别 API 简介 -- Simpletex 使用 Python web 部署库 waitress 3D Gaussian Splatting for Real-Time Radiance Field Rendering Ubuntu Swap 简介与空间扩展 Ubuntu 24.04 安装 forticlient Clash Verge 使用 MongoDB 7.0.17 集群 Docker 构建源码 Error code - 2013. Lost connection to MySQL server during query 问题解决 Python 日志记录库 loguru 使用指北 Python 实现 Web 日志查看服务 MySQL LOAD DATA LOCAL INFILE 极速数据加载 Image size exceeds limit of 89478485 pixels 解决方案 Docker 使用 NVIDIA GPU 驱动错误解决 阿里云 docker 镜像仓库 Ubuntu中没有wired connected的解决方案 MinIO 简介 subconverter 代理订阅格式转换 修复 node –openssl-legacy-provider is not allowed in NODE_OPTIONS 错误 Ubuntu 使用 Clash For Linux 客户端
Python matplotlib 图表绘制
Yiwei Zhang · 2025-08-19 · via 又见苍岚
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import numpy as np
import os
from matplotlib import patheffects
from matplotlib.ticker import FuncFormatter
import matplotlib.font_manager as fm
import pathlib
import warnings
from io import BytesIO # 新增用于内存操作
import PIL.Image # 新增用于图像处理
from loguru import logger
import vvdutils as vv

class ChartPainter:
def __init__(self, chart, x_axis, y_axis, series, grid, legend, time={}, theme_settings={}, radar_axis={}):
self.chart = chart
self.x_axis = x_axis
self.y_axis = y_axis
self.series = series
self.grid = grid
self.legend = legend
self.time = time
self.theme_settings = theme_settings
self.radar_axis = radar_axis

# 1. 设置支持中文的字体
self._load_custom_font()

def paint(self, show=False):
"""绘制图表"""
chart_type = self.chart.get('type', 'line').lower()

if chart_type == 'line':
return self.line(show)
elif chart_type == 'bar':
return self.bar(show)
elif chart_type == 'combo':
return self.combo(show)
elif chart_type == 'stacked_bar':
return self.stacked_bar(show)
elif chart_type == 'radar':
return self.radar(show)
else:
raise ValueError(f"Unsupported chart type: {chart_type}")

def _load_custom_font(self):
"""手动加载自定义字体文件"""
font_path = str(pathlib.Path(__file__).parent / 'fonts' / 'wqy-microhei.ttc') # 假设字体文件在lib/fonts目录下
try:
# 检查文件是否存在
if not os.path.exists(font_path):
warnings.warn(f"字体文件不存在: {font_path}")
return

# 获取字体属性
font_prop = fm.FontProperties(fname=font_path)
font_name = font_prop.get_name()

# 将字体添加到Matplotlib字体管理器
fm.fontManager.addfont(font_path)

# 设置全局字体
plt.rcParams['font.family'] = font_name
plt.rcParams['axes.unicode_minus'] = False
logger.debug(f" @@ 成功加载自定义字体: {font_name}")

except Exception as e:
warnings.warn(f"加载字体失败: {str(e)}")

def _setup_common_styles(self, ax):
"""通用样式设置(添加中文支持)"""
# 网格样式
if self.grid['visible']:
grid_style = self.grid['style']
linestyle = '-' if grid_style == '-' else '--' if grid_style == '--' else ':' if grid_style == ':' else '-.'
ax.grid(True, linestyle=linestyle, alpha=0.3, color=self.theme_settings.get('grid_color', '#493D3D'))

# 坐标轴标签和标题 - 添加中文字体支持
ax.set_xlabel(self.x_axis['label'], fontsize=12,
color=self.theme_settings.get('axis_label_color', "#493D3D"), labelpad=10)
ax.set_ylabel(self.y_axis['label'], fontsize=12,
color=self.theme_settings.get('axis_label_color', "#493D3D"), labelpad=10)
ax.set_title(self.chart['title'], fontsize=16,
color=self.theme_settings.get('axis_label_color', "#493D3D"), pad=20)

# 刻度样式 - 确保中文显示
ax.tick_params(axis='x', colors=self.theme_settings.get('axis_label_color', "#493D3D"))
ax.tick_params(axis='y', colors=self.theme_settings.get('axis_label_color', "#493D3D"))

# 边框样式
for spine in ax.spines.values():
spine.set_color(self.theme_settings.get('spine_color', 'white'))
spine.set_linewidth(1.5)

# 图例样式 - 支持中文
legend_pos = self.legend['position']
legend = ax.legend(
facecolor=self.theme_settings.get('legend_background_color', '#3d3d3d'),
edgecolor='none',
framealpha=0.8,
loc=legend_pos,
bbox_to_anchor=(1, 1) if legend_pos == 'upper right' else None,
ncol=len(self.series) if self.legend['direction'] == 'horizontal' else 1,
prop={'family': plt.rcParams['font.family']} # 确保图例使用中文字体
)
for text in legend.get_texts():
text.set_color(self.theme_settings.get('legend_text_color', '#FFFFFF'))

# 添加时间范围页脚 - 支持中文
self._add_time_area()

def _set_figure_size(self):
"""设置图表大小"""
width, height = self.chart['size']
temp_width = 16
height_size = max(3, temp_width / width * height)

# 创建新的图形
fig = plt.figure(figsize=(temp_width, height_size),
facecolor=self.theme_settings.get('facecolor', "#FFFFFF"))
fig.dpi = width / temp_width
return fig

def _figure_to_numpy(self, fig, show=False):
"""将matplotlib图形转换为NumPy数组"""
# 创建一个内存缓冲区
buf = BytesIO()

# 保存图像到缓冲区
fig.savefig(buf, format='png', dpi=fig.dpi, pad_inches=0.1)

# 将缓冲区指针重置到开始位置
buf.seek(0)

# 使用PIL打开图像并转换为NumPy数组
img = PIL.Image.open(buf)
img_array = np.array(img)

# 关闭缓冲区
buf.close()

# 关闭图形释放内存
plt.close(fig)

img_array = img_array[:, :, :3] # 去掉alpha通道

logger.info(f" @@ 图像定义尺寸: {self.chart['size']},实际尺寸: {img_array.shape}")
resized_array = vv.image_resize(img_array, self.chart['size'])

if show:
vv.PIS(resized_array)

return resized_array

def line(self, show=False):
"""绘制折线图,返回NumPy数组图像"""
fig = self._set_figure_size()
ax = fig.add_subplot(111)
ax.set_facecolor(self.theme_settings.get('axes_facecolor', "#f1f1f1"))

# 处理日期型x轴
x = self._process_x_axis()

for series_data in self.series:
# 绘制折线
line = ax.plot(x, series_data['data'],
label=series_data['name'],
color=series_data['color'],
linewidth=3,
marker='o',
markersize=8,
markerfacecolor=self.theme_settings.get('marker_facecolor', "#FFFFFF"),
markeredgewidth=2)

# 添加数据标签
self._add_data_labels(ax, x, series_data)

# 设置y轴范围
if 'range' in self.y_axis:
ax.set_ylim(self.y_axis['range'][0], self.y_axis['range'][1])

self._setup_common_styles(ax)
self._add_glow_effect(ax)
plt.tight_layout()

# 返回NumPy数组图像
return self._figure_to_numpy(fig, show)

def bar(self, show=False):
"""绘制柱状图,返回NumPy数组图像"""
fig = self._set_figure_size()
ax = fig.add_subplot(111)
ax.set_facecolor(self.theme_settings.get('axes_facecolor', "#f1f1f1"))

# 处理日期型x轴
x = self._process_x_axis()
x_pos = np.arange(len(x))

# 计算柱宽和位置(分组柱状图)
bar_width = 0.8 / len(self.series)
offsets = np.linspace(-0.4 + bar_width/2, 0.4 - bar_width/2, len(self.series))

for idx, series_data in enumerate(self.series):
# 绘制柱状图
bars = ax.bar(x_pos + offsets[idx], series_data['data'],
width=bar_width,
label=series_data['name'],
color=series_data['color'],
edgecolor=self.theme_settings.get('bar_edgecolor', 'white'),
linewidth=1,
alpha=0.9)

# 添加数据标签
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.0f}',
ha='center', va='bottom',
color=self.theme_settings.get('text_color', '#333333'),
fontsize=9)

# 设置x轴刻度和范围
ax.set_xticks(x_pos)
ax.set_xticklabels(x)
if self.x_axis['type'] == 'date':
plt.xticks(rotation=45, ha='right')

# 设置y轴范围
if 'range' in self.y_axis:
ax.set_ylim(self.y_axis['range'][0], self.y_axis['range'][1])
else:
# 自动调整y轴上限
max_val = max(max(s['data']) for s in self.series)
ax.set_ylim(0, max_val * 1.15)

# 添加千分位分隔符
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: f'{x:,.0f}'))

self._setup_common_styles(ax)
plt.tight_layout()

# 返回NumPy数组图像
return self._figure_to_numpy(fig, show)

def _process_x_axis(self):
"""处理x轴数据(日期/字符串)"""
if self.x_axis['type'] == 'date':
return [datetime.strptime(d, '%Y-%m-%d') for d in self.x_axis['categories']]
return self.x_axis['categories']

def _add_data_labels(self, ax, x, series_data):
"""添加数据标签"""
for i, (xi, yi) in enumerate(zip(x, series_data['data'])):
ax.text(xi, yi+2, f'{yi:.0f}',
color=self.theme_settings.get('text_color', "#200606"),
ha='center',
va='bottom',
fontsize=9,
bbox=dict(facecolor=series_data['color'], alpha=0.7,
edgecolor='none', boxstyle='round,pad=0.2'))

def _add_glow_effect(self, ax):
"""添加发光效果"""
for line in ax.lines:
line.set_path_effects([
patheffects.Stroke(linewidth=5, foreground=line.get_color(), alpha=0.5),
patheffects.Normal()
])

def _add_time_area(self):
# 添加时间范围页脚 - 支持中文
if 'start_time' in self.time:
time_text = f"数据范围: {self.time['start_time']}{self.time['end_time']}"
plt.figtext(0.002 * len(time_text), 0.02, time_text,
ha='center',
fontsize=5,
color=self.theme_settings.get('text_color', '#493D3D'),
bbox=dict(facecolor=self.theme_settings.get('footer_background', '#3d3d3d'),
alpha=0.1, edgecolor='none'))

def combo(self, show=False):
"""绘制组合图表(柱状图+折线图),返回NumPy数组图像"""
fig = self._set_figure_size()
ax = fig.add_subplot(111)
ax.set_facecolor(self.theme_settings.get('axes_facecolor', "#f1f1f1"))

# 处理日期型x轴
x = self._process_x_axis()
x_pos = np.arange(len(x))

# 分离柱状图和折线图系列
bar_series = [s for s in self.series if s['type'] == 'bar']
line_series = [s for s in self.series if s['type'] == 'line']

# 绘制柱状图部分
if bar_series:
bar_width = 0.8 / len(bar_series)
offsets = np.linspace(-0.4 + bar_width/2, 0.4 - bar_width/2, len(bar_series))

for idx, series_data in enumerate(bar_series):
bars = ax.bar(x_pos + offsets[idx], series_data['data'],
width=bar_width,
label=series_data['name'],
color=series_data['color'],
edgecolor=self.theme_settings.get('bar_edgecolor', 'white'),
linewidth=1,
alpha=series_data.get('alpha', 0.9))

# 添加数据标签
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.0f}',
ha='center', va='bottom',
color=self.theme_settings.get('text_color', '#333333'),
fontsize=9)

# 绘制折线图部分(使用次坐标轴)
if line_series:
ax2 = ax.twinx()
for series_data in line_series:
line = ax2.plot(x_pos, series_data['data'],
label=series_data['name'],
color=series_data['color'],
linewidth=3,
marker='o',
markersize=8,
markerfacecolor=self.theme_settings.get('marker_facecolor', "#FFFFFF"),
markeredgewidth=2)

# 添加数据标签
for i, (xi, yi) in enumerate(zip(x_pos, series_data['data'])):
ax2.text(xi, yi, f'{yi:.1f}',
color=self.theme_settings.get('text_color', "#200606"),
ha='center',
va='bottom' if yi < max(series_data['data'])*0.8 else 'top',
fontsize=9,
bbox=dict(facecolor=series_data['color'], alpha=0.7,
edgecolor='none', boxstyle='round,pad=0.2'))

# 设置右侧y轴样式
ax2.spines['right'].set_color(self.theme_settings.get('axis_label_color', "#493D3D"))
ax2.tick_params(axis='y', colors=self.theme_settings.get('axis_label_color', "#493D3D"))
if line_series[0].get('y_axis_label'):
ax2.set_ylabel(line_series[0]['y_axis_label'],
color=self.theme_settings.get('axis_label_color', "#493D3D"))

# 设置x轴刻度和范围 - 优化日期标签显示
ax.set_xticks(x_pos)
if self.x_axis['type'] == 'date':
# 智能日期格式化
if len(x) > 10: # 如果数据点多,使用简写月份
ax.set_xticklabels([d.strftime('%b %d') for d in x])
else:
ax.set_xticklabels([d.strftime('%b %d, %Y') for d in x])

# 自动调整标签旋转角度和间隔
if len(x) > 8:
plt.xticks(rotation=30, ha='right')
# 稀疏显示标签(每隔n个显示一个)
ax.set_xticks(ax.get_xticks()[::max(1, len(x)//8)])
else:
ax.set_xticklabels(x)
if len(x) > 10:
plt.xticks(rotation=45, ha='right')

# 设置主y轴范围
if 'range' in self.y_axis:
ax.set_ylim(self.y_axis['range'][0], self.y_axis['range'][1])
elif bar_series:
max_val = max(max(s['data']) for s in bar_series)
ax.set_ylim(0, max_val * 1.15)

# 添加千分位分隔符
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: f'{x:,.0f}'))

# 应用通用样式
self._setup_common_styles(ax)

# 特殊处理组合图图例
if line_series:
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend_.remove() # 移除自动生成的图例
ax.legend(lines + lines2, labels + labels2,
facecolor=self.theme_settings.get('legend_background_color', '#3d3d3d'),
edgecolor='none',
framealpha=0.8,
loc=self.legend['position'])

plt.tight_layout()

# 返回NumPy数组图像
return self._figure_to_numpy(fig, show)

def stacked_bar(self, show=False):
"""绘制分组堆叠柱状图,返回NumPy数组图像"""
fig = self._set_figure_size()
ax = fig.add_subplot(111)
ax.set_facecolor(self.theme_settings.get('axes_facecolor', "#f1f1f1"))

# 处理日期型x轴
x_categories = self._process_x_axis()
num_categories = len(x_categories)

# 检查堆叠组并排序以确保一致性
stack_groups = {}
for series in self.series:
if 'stack' in series:
if series['stack'] not in stack_groups:
stack_groups[series['stack']] = []
stack_groups[series['stack']].append(series)

# 如果没有堆叠组,则所有系列堆叠在一起
if not stack_groups:
stack_groups['default_stack'] = self.series

# 获取所有堆叠组名称并排序
stack_names = sorted(stack_groups.keys())
num_stacks = len(stack_names)

# 设置柱状图位置和宽度
total_width = 0.8 # 每组柱状图的总宽度
bar_width = total_width / num_stacks
bar_positions = np.arange(num_categories)

# 颜色映射 - 为每个堆叠组分配颜色
stack_colors = {}
for stack_name in stack_names:
# 使用组内第一个系列的颜色作为整个堆叠组的颜色
stack_colors[stack_name] = stack_groups[stack_name][0]['color']

# 绘制分组堆叠柱状图
for stack_idx, stack_name in enumerate(stack_names):
# 计算当前堆叠组的位置偏移
offset = (stack_idx - (num_stacks - 1) / 2) * bar_width

# 初始化底部位置
bottom = np.zeros(num_categories)

# 绘制当前堆叠组内的所有系列
for series_data in stack_groups[stack_name]:
# 计算当前柱状图位置
positions = bar_positions + offset

# 绘制堆叠柱状图
bars = ax.bar(positions, series_data['data'],
width=bar_width,
bottom=bottom,
label=f"{stack_name}: {series_data['name']}",
color=series_data['color'],
edgecolor=self.theme_settings.get('bar_edgecolor', 'white'),
linewidth=1,
alpha=series_data.get('alpha', 0.9))

# 添加数据标签
for i, bar in enumerate(bars):
height = series_data['data'][i]
if height > 0: # 只显示有高度的标签
y_pos = bottom[i] + height/2
ax.text(bar.get_x() + bar.get_width()/2.,
y_pos,
f'{height:.0f}',
ha='center', va='center',
color=self.theme_settings.get('text_color', '#333333'),
fontsize=9)

# 更新底部位置
bottom += np.array(series_data['data'])

# 设置x轴刻度和范围
ax.set_xticks(bar_positions)

# 设置x轴标签
if self.x_axis['type'] == 'date':
# 智能日期格式化
if num_categories > 10: # 如果数据点多,使用简写月份
ax.set_xticklabels([d.strftime('%b %d') for d in x_categories])
else:
ax.set_xticklabels([d.strftime('%b %d, %Y') for d in x_categories])

# 自动调整标签旋转角度
plt.xticks(rotation=45, ha='right')
else:
ax.set_xticklabels(x_categories)
if num_categories > 10:
plt.xticks(rotation=45, ha='right')

# 设置y轴范围
max_val = max([sum(series['data']) for stack in stack_groups.values() for series in stack]) * 1.1
if 'range' in self.y_axis:
ax.set_ylim(self.y_axis['range'][0], self.y_axis['range'][1])
else:
ax.set_ylim(0, max_val)

# 添加千分位分隔符
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: f'{x:,.0f}'))

# 添加分组图例
stack_legend_handles = []
for stack_name in stack_names:
# 创建图例条目
handle = plt.Rectangle((0,0), 1, 1,
color=stack_colors[stack_name],
alpha=0.7,
label=stack_name)
stack_legend_handles.append(handle)

# 添加堆叠组图例
if stack_legend_handles:
# 获取原始图例位置
legend_pos = self.legend['position']

# 添加堆叠组图例
stack_legend = ax.legend(
handles=stack_legend_handles,
title="堆叠组",
facecolor=self.theme_settings.get('legend_background_color', '#3d3d3d'),
edgecolor='none',
framealpha=0.8,
loc='upper left',
bbox_to_anchor=(1.05, 1) if legend_pos == 'upper right' else (0, 1)
)

# 应用通用样式
self._setup_common_styles(ax)
plt.tight_layout()

# 返回NumPy数组图像
return self._figure_to_numpy(fig, show)

def radar(self, show=False):
"""绘制雷达图,返回NumPy数组图像"""
fig = self._set_figure_size()

# 获取雷达图维度
dimensions = self.radar_axis.get('dimensions', [])
if not dimensions:
raise ValueError("Radar chart requires 'radar_axis.dimensions' in chart config")

# 计算角度
angles = np.linspace(0, 2*np.pi, len(dimensions), endpoint=False).tolist()
angles += angles[:1] # 闭合图形

# 创建极坐标子图
ax = fig.add_subplot(111, polar=True)

# 绘制每个系列
for series_data in self.series:
values = series_data['data']
values += values[:1] # 闭合图形

# 绘制雷达图线条
ax.plot(angles, values,
linewidth=2,
linestyle='solid',
label=series_data['name'],
color=series_data['color'])

# 填充颜色
ax.fill(angles, values,
color=series_data['color'],
alpha=0.2)

# 添加数据标签
for angle, value, dim in zip(angles[:-1], series_data['data'], dimensions):
ax.text(angle, value*1.05, f'{value:.1f}',
color=series_data['color'],
ha='center', va='center',
fontsize=9,
bbox=dict(facecolor='white', alpha=0.7,
edgecolor='none', boxstyle='round,pad=0.2'))

# 设置极坐标轴
ax.set_theta_offset(np.pi / 2) # 0度在顶部
ax.set_theta_direction(-1) # 顺时针方向

# 设置维度标签
ax.set_xticks(angles[:-1])
ax.set_xticklabels(dimensions,
color=self.theme_settings.get('axis_label_color', "#493D3D"))

# 设置径向轴
max_margin = 1.2 # 边距

if 'max_value' in self.radar_axis:
radar_max_value = self.radar_axis['max_value']
else:
max_val = max(max(s['data']) for s in self.series) if self.series else 1
radar_max_value = max_val * max_margin

ax.set_rlabel_position(30) # 径向标签位置
ax.set_yticks(np.linspace(0, radar_max_value, 5))
ax.set_yticklabels([f"{tick:.1f}" for tick in np.linspace(0,radar_max_value, 5)],
color=self.theme_settings.get('axis_label_color', "#493D3D"))
ax.set_ylim(0, radar_max_value)

# 设置标题和图例
ax.set_title(self.chart['title'],
pad=20,
color=self.theme_settings.get('axis_label_color', "#493D3D"),
fontsize=16)

# 图例样式
legend = ax.legend(
facecolor=self.theme_settings.get('legend_background_color', '#3d3d3d'),
edgecolor='none',
framealpha=0.8,
loc=self.legend['position'],
bbox_to_anchor=(1.1, 1) if self.legend['position'] == 'upper right' else None
)
for text in legend.get_texts():
text.set_color(self.theme_settings.get('legend_text_color', '#FFFFFF'))

# 添加时间范围页脚 - 支持中文
self._add_time_area()

plt.tight_layout()

# 返回NumPy数组图像
return self._figure_to_numpy(fig, show)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
from lib import ChartPainter

theme_settings = {
"facecolor": "#F5F7FA",
"axes_facecolor": "#FFFFFF",
"text_color": "#333333",
"axis_label_color": "#4A6FA5",
"grid_color": "#E1E5EB",
"legend_background_color": "#FFFFFF",
"legend_text_color": "#333333",
"spine_color": "#C1C9D6",
"bar_edgecolor": "#FFFFFF",
"footer_background": "#493808"
}

# 雷达图测试数据
radar_chart_data = {
"theme_settings": theme_settings,

"chart": {
"type": "radar",
"title": "Product Performance Comparison",
"size": [4000, 3000],
},
"radar_axis": {
"dimensions": ["中文设计", "Functionality嘟嘟读", "Usability", "Performance", "Support", "Compatibility"],
"max_value": 15
},
"x_axis": {},
"y_axis": {},
"series": [
{
"name": "Product A嘟嘟读",
"data": [4.5, 4.2, 4.7, 4.3, 4.1, 14.6],
"color": "#4E79A7"
},
{
"name": "Product B嘟嘟读",
"data": [3.8, 4.5, 4.1, 4.6, 3.9, 14.2],
"color": "#F28E2B"
},
{
"name": "Industry Average",
"data": [4.0, 4.0, 4.0, 4.0, 4.0, 4.0],
"color": "#59A14F",
}
],
"grid": {
"visible": True
},
"legend": {
"position": "upper right",
"direction": "vertical"
},
"time": {
"start_time": "2023-01-01",
"end_time": "2023-12-31"
}
}

# 使用示例
painter = ChartPainter(**radar_chart_data)
painter.paint(True)

# 堆叠柱状图测试数据
stacked_bar_data = {
"theme_settings": theme_settings,
"chart": {
"type": "stacked_bar",
"title": "Quarterly Sales by Product Category (2023)嘟嘟读",
"size": [2000, 500]
},
"x_axis": {
"label": "Quarter",
"type": "string",
"categories": ["Q1", "Q2", "Q3", "Q4"]
},
"y_axis": {
"label": "Sales (thousand $)",
"range": [0, 1000]
},
"series": [
{
"name": "Electronics",
"data": [120, 150, 130, 180],
"color": "#4E79A7",
"stack": "category"
},
{
"name": "Clothing嘟嘟读",
"data": [80, 90, 95, 110],
"color": "#F28E2B",
"stack": "category"
},
{
"name": "Home Goods嘟嘟读",
"data": [60, 70, 75, 90],
"color": "#E15759",
"stack": "category"
},
{
"name": "Online",
"data": [150, 180, 170, 220],
"color": "#76B7B2",
"stack": "channel"
},
{
"name": "Offline",
"data": [110, 130, 130, 160],
"color": "#59A14F",
"stack": "channel"
}
],
"grid": {
"visible": True,
"style": "--"
},
"legend": {
"position": "upper right",
"direction": "vertical"
},
"time": {
"start_time": "2023-01-01",
"end_time": "2023-12-31"
}
}

# 使用示例
painter = ChartPainter(**stacked_bar_data)
painter.paint(True)

# 日期型堆叠柱状图数据
date_stacked_data = {
"theme_settings": theme_settings,
"chart": {
"type": "stacked_bar",
"title": "Monthly Website Traffic Sources (2023)",
"size": [2000, 900],
"save_path": "traffic_sources.png"
},
"x_axis": {
"label": "Month",
"type": "date",
"categories": [
"2023-01-01", "2023-02-01", "2023-03-01",
"2023-04-01", "2023-05-01", "2023-06-01"
]
},
"y_axis": {
"label": "Visitors (thousands)"
},
"series": [
{
"name": "Organic Search",
"data": [45, 48, 52, 55, 58, 62],
"color": "#4E79A7",
"stack": "source"
},
{
"name": "Direct",
"data": [30, 32, 35, 38, 40, 42],
"color": "#F28E2B",
"stack": "source"
},
{
"name": "Social Media",
"data": [20, 22, 25, 28, 30, 32],
"color": "#E15759",
"stack": "source"
},
{
"name": "Referral",
"data": [15, 18, 20, 22, 25, 28],
"color": "#76B7B2",
"stack": "source"
}
],
"grid": {
"visible": True,
"style": ":"
},
"legend": {
"position": "upper left",
"direction": "vertical"
},
"time": {
"start_time": "2023-01-01",
"end_time": "2023-06-30"
}
}

# 使用示例
painter = ChartPainter(**date_stacked_data)
painter.paint(True)

# 组合图表测试数据(销售额柱状图+增长率折线图)
combo_chart_data = {
"theme_settings": theme_settings,
"chart": {
"type": "combo",
"title": "Monthly Sales & Growth Rate (2023)",
"size": [1800, 800]
},
"x_axis": {
"label": "Month",
"type": "string",
"categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
},
"y_axis": {
"label": "Sales (thousand $)",
"range": [0, 180]
},
"series": [
{
"name": "Sales Amount",
"type": "bar",
"data": [85, 78, 92, 105, 98, 112, 125, 118, 132, 145, 138, 152],
"color": "#4E79A7"
},
{
"name": "Growth Rate (%)",
"type": "line",
"data": [0, -8.2, 17.9, 14.1, -6.7, 14.3, 11.6, -5.6, 11.9, 9.8, -4.8, 10.1],
"color": "#E15759",
"y_axis_label": "Growth Rate %"
}
],
"grid": {
"visible": True,
"style": "--"
},
"legend": {
"position": "upper left",
"direction": "horizontal"
},
"time": {
"start_time": "2023-01-01",
"end_time": "2023-12-31"
}
}

# 使用示例
painter = ChartPainter(**combo_chart_data)
painter.paint(True)

# 日期型组合图表数据(网站流量柱状图+转化率折线图)
date_combo_data = {
"theme_settings": theme_settings,
"chart": {
"type": "combo",
"title": "Weekly Performance (Q1 2023)",
"size": [2000, 500],
"save_path": "weekly_performance.png"
},
"x_axis": {
"label": "Week",
"type": "date",
"categories": [
"2023-01-02", "2023-01-09", "2023-01-16", "2023-01-23", "2023-01-30",
"2023-02-06", "2023-02-13", "2023-02-20", "2023-02-27",
"2023-03-06", "2023-03-13", "2023-03-20", "2023-03-27"
]
},
"y_axis": {
"label": "Visitors (thousands)",
"range": [0, 230]
},
"series": [
{
"name": "Total Visitors",
"type": "bar",
"data": [125, 132, 118, 145, 138, 152, 165, 158, 172, 185, 178, 192, 205],
"color": "#F06595"
},
{
"name": "Total Visitors2",
"type": "bar",
"data": [125, 132, 118, 145, 138, 152, 165, 158, 172, 185, 178, 192, 205],
"color": "#20C97A"
},
{
"name": "Total Visitors3",
"type": "bar",
"data": [125, 132, 118, 145, 138, 152, 165, 158, 172, 185, 178, 192, 205],
"color": "#3120C9"
},
{
"name": "Conversion Rate (%)",
"type": "line",
"data": [2.8, 3.1, 2.9, 3.5, 3.2, 3.7, 4.0, 3.8, 4.2, 4.5, 4.3, 4.6, 5.0],
"color": "#5C7CFA",
}
],
"grid": {
"visible": True,
"style": ":"
},
"legend": {
"position": "upper right",
"direction": "vertical"
},
"time": {
"start_time": "2023-01-01",
"end_time": "2023-03-31"
}
}

# 使用示例
painter = ChartPainter(**date_combo_data)
painter.paint(True)

# 日期型折线图数据
date_bar_data = {
"theme_settings": theme_settings,
"chart": {
"type": "line",
"title": "Weekly Website Traffic (Jan-Mar 2023)",
"size": [2000, 900]
},
"x_axis": {
"label": "Week",
"type": "date",
"categories": [
"2023-01-02", "2023-01-09", "2023-01-16", "2023-01-23", "2023-01-30",
"2023-02-06", "2023-02-13", "2023-02-20", "2023-02-27",
"2023-03-06", "2023-03-13", "2023-03-20", "2023-03-27"
]
},
"y_axis": {
"label": "Visitors (thousands)"
},
"series": [
{
"name": "New Visitors",
"data": [45, 52, 48, 55, 50, 58, 65, 62, 68, 72, 78, 75, 82],
"color": "#6C8EBF"
},
{
"name": "Returning Visitors",
"data": [85, 92, 88, 95, 102, 108, 115, 122, 118, 125, 132, 128, 135],
"color": "#82B366"
}
],
"grid": {
"visible": True,
"style": ":"
},
"legend": {
"position": "upper left",
"direction": "vertical"
},
"time": {
"start_time": "2023-01-01",
"end_time": "2023-03-31"
}
}

# 使用示例
painter = ChartPainter(**date_bar_data)
painter.paint(True)

# Example usage
data = {
"theme_settings": theme_settings,
"chart": {
"type": "line",
"title": "Monthly Sales Performance (2023)",
"size": [2000, 700]
},
"x_axis": {
"label": "Month",
"type": "string",
"categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
},
"y_axis": {
"label": "Sales (in thousands)",
"range": [0, 120]
},
"series": [
{
"name": "Product A",
"data": [45, 58, 36, 74, 52, 69, 84, 97, 68, 76, 89, 94],
"color": "#4E79A7"
},
{
"name": "Product B",
"data": [28, 33, 45, 57, 62, 78, 65, 72, 85, 91, 78, 105],
"color": "#F28E2B"
},
{
"name": "Product C",
"data": [15, 22, 38, 42, 56, 61, 73, 68, 74, 82, 95, 88],
"color": "#E15759"
}
],
"grid": {
"visible": True,
"style": "--"
},
"legend": {
"position": "upper right",
"direction": "horizontal"
},
"time": {
"start_time": "2023-01-01 00:00:00",
"end_time": "2023-12-31 23:59:59"
}
}

painter = ChartPainter(**data)
painter.paint(True)

# 柱状图测试数据
bar_chart_data = {
"theme_settings": theme_settings,
"chart": {
"type": "bar",
"title": "Quarterly Revenue Comparison (2022-2023)",
"size": [1600, 900]
},
"x_axis": {
"label": "Quarter",
"type": "string",
"categories": ["Q1", "Q2", "Q3", "Q4"]
},
"y_axis": {
"label": "Revenue (million $)",
"range": [0, 300]
},
"series": [
{
"name": "2022",
"data": [125, 145, 132, 185],
"color": "#4C72B0"
},
{
"name": "2023",
"data": [155, 178, 162, 210],
"color": "#55A868"
},
{
"name": "Target",
"data": [140, 160, 150, 200],
"color": "#DD8452"
}
],
"grid": {
"visible": True,
"style": "--"
},
"legend": {
"position": "upper right",
"direction": "horizontal"
},
"time": {
"start_time": "2022-01-01",
"end_time": "2023-12-31"
}
}

# 使用示例
painter = ChartPainter(**bar_chart_data)
painter.paint(True)

# 日期型柱状图数据
date_bar_data = {
"theme_settings": theme_settings,
"chart": {
"type": "bar",
"title": "Weekly Website Traffic (Jan-Mar 2023)",
"size": [2000, 900]
},
"x_axis": {
"label": "Week",
"type": "date",
"categories": [
"2023-01-02", "2023-01-09", "2023-01-16", "2023-01-23", "2023-01-30",
"2023-02-06", "2023-02-13", "2023-02-20", "2023-02-27",
"2023-03-06", "2023-03-13", "2023-03-20", "2023-03-27"
]
},
"y_axis": {
"label": "Visitors (thousands)"
},
"series": [
{
"name": "New Visitors",
"data": [45, 52, 48, 55, 50, 58, 65, 62, 68, 72, 78, 75, 82],
"color": "#6C8EBF"
},
{
"name": "Returning Visitors",
"data": [85, 92, 88, 95, 102, 108, 115, 122, 118, 125, 132, 128, 135],
"color": "#82B366"
}
],
"grid": {
"visible": True,
"style": ":"
},
"legend": {
"position": "upper left",
"direction": "vertical"
},
"time": {
"start_time": "2023-01-01",
"end_time": "2023-03-31"
}
}

# 使用示例
painter = ChartPainter(**date_bar_data)
painter.paint(True)