本文最后更新于:2025年8月19日 下午

本文记录一个可以绘制折线图、柱状图、堆叠柱状图、雷达图、折线柱状图的一个管理者。

图表绘制

设计思想:

  1. 复用输入表结构
  2. 复用初始化结构
  3. 复用尺寸配置
  4. 复用图片输出配置
  5. 根据类型自适应生成图表
  6. 自定义中文字体支持

核心源码

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)
  • 雷达图

  • 分组堆叠柱状图

  • 柱状折线图

  • 折线图

  • 柱状图



文章链接:
https://www.zywvvd.com/notes/coding/python/matplotlib-manager/matplotlib-manager/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

Python matplotlib 图表绘制
https://www.zywvvd.com/notes/coding/python/matplotlib-manager/matplotlib-manager/
作者
Yiwei Zhang
发布于
2025年8月19日
许可协议