matplotlib是常用的可视化库,画折线图只要把列表plot进去就可以轻松展示,这里只弄折线图,其它图暂时不管。同一图上不同曲线数值大小差太多就能绘制成地板和天花板还不能给人家量纲去了,所以不同曲线需要不同纵轴才能清晰看出细小波动~
要是觉得颜色不好看还可以指定几个颜色,这些颜色按照与数据序列相同的顺序作用于对应曲线。
matplotlib怎么作图,用一次搜一次每次只要import matplotlib就搜,写个常用工具别再搜了
import random
from typing import Iterable
import matplotlib.pyplot as plt
from mpl_toolkits.axisartist.parasite_axes import HostAxes, ParasiteAxes
def hsv_to_rgb(h, s, v):
c = v * s
x = c * (1 - abs(int(h/60) % 2-1))
m = v - c
if 0 <= h < 60:
r, g, b = c, x, 0
elif 60 <= h < 120:
r, g, b = x, c, 0
elif 120 <= h < 180:
r, g, b = 0, c, x
elif 180 <= h < 240:
r, g, b = 0, x, c
elif 240 <= h < 300:
r, g, b = x, 0, c
elif 300 <= h < 360:
r, g, b = c, 0, x
r, g, b = r + m, g + m, b + m
return r, g, b
def plot(data: 'dict[str,Iterable]', axis_distance: int = 40, x_label: str = None, colors: Iterable = None, padding: float = .1):
"""多曲线展示
Parameters
----------
data : dict[str,Iterable]
待展示数据
axis_distance : int, optional
坐标轴间距, by default 40
x_label : str, optional
横轴标签, by default None
colors : Iterable, optional
候选色彩,若色彩数量不足以显示曲线则分配不到色彩的曲线用随机颜色, by default None
"""
fig = plt.figure(1)
ax_base = HostAxes(fig, [padding, padding, 1 - padding * 2, 1 - padding * 2])
ax_base.axis['right'].set_visible(False)
ax_base.axis['top'].set_visible(False)
color_list = [hsv_to_rgb(h, random.random() * .2 + .6, random.random() * .2 + .7) for h in range(0, 360, 30)]
random.shuffle(color_list)
color_list = [ele for ele in colors or []]+color_list
random_color_count = len(data.keys())-len(color_list)
if random_color_count > 0:
color_list += [hsv_to_rgb(random.randint(0, 360-1), random.random() * .2 + .6, random.random() * .2 + .7) for _ in range(random_color_count)]
color_list.reverse()
index = 0
for label, value in data.items():
color = color_list.pop()
if index:
axe = ParasiteAxes(ax_base, sharex=ax_base)
axe.set_ylabel(label)
ax_base.parasites.append(axe)
axisline = axe.get_grid_helper().new_fixed_axis
key_name = '?'+label
axe.axis[key_name] = axisline(loc='right', axes=axe, offset=((index - 1) * axis_distance, 0))
axe.plot(value, label=label, color=color)
axe.axis[key_name].label.set_color(color)
axe.axis[key_name].major_ticks.set_color(color)
axe.axis[key_name].major_ticklabels.set_color(color)
axe.axis[key_name].line.set_color(color)
else:
if x_label:
ax_base.set_xlabel(x_label)
ax_base.set_ylabel(label)
ax_base.plot(value, label=label, color=color)
index += 1
fig.add_axes(ax_base)
ax_base.legend()
plt.show()