plt | 双轴布局

#%%
# CY3761 | 2022-01-20 13:33
#%%
# 此为 jupyter 模版, 执行 build 后记住先执行-全部运行
# 使用 DataSpell 进行编写文档
# 变量名、函数名小写分段处理
#%%
# 导入项
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import types

# 设置全局参数
plt.rcParams['font.family'] = plt.rcParams['font.sans-serif'] = 'SimHei' # 设置字体 国标黑体中文字体
plt.rcParams['axes.unicode_minus'] = False ## 设置正常显示符号

np.array((np, pd, plt))
#%%
class JsonObject:
    def __init__(self, items):
        self.items = items

    def __getattribute__(self, name: str):  # 注意这个方法有个坑里面不能写入 self.* 否则会出现 循环调用
        return object.__getattribute__(self, 'items').get(name)


def print_data(o, head=True):
    o_items = dict(shape=None,size=None, index=None,columns=None, dtype=None,dtypes=None,)

    print('type\t: %s' % type(o))

    for (k,v) in o_items.items():
        try:
            o_items[k] = eval(f'o.{k}')
        except (Exception, BaseException):
            pass

        if k == 'dtypes':
            o_items[k] = {k:str(v) for k,v in dict(o_items[k]).items() }

        print('%s\t: %s' % (k, o_items[k]))

    print()

    objs = o

    if head:
        objs = objs.head(head if type(head) is int else 5)  # 这里不能 isinstance(head, int) 布尔值也是返回True

    display(objs)

def get_new_file_path(file_path, string, file_ext=None):
    file_sep = '.'
    file_path_split = file_path.split(file_sep)
    file_path_split_pop = file_path_split.pop()  # 获取最后一个
    file_ext = file_path_split_pop if not file_ext else file_ext

    return file_sep.join(file_path_split) + '-' + string + file_sep + file_ext

r_rang = 26
r_chr = {k: [chr(_) for _ in range(size, size+r_rang)] for k,size in dict(b=65, s=97).items()}  # 大写字母索引 小写字母索引
r_chr = pd.DataFrame(r_chr, index=range(1, r_rang+1))  # 字母表 b: 大写 s: 小写 1 开始

def get_chr_items(k, f):
    k = k.lower()
    f = f.upper() if k == 'b' else f.lower()

    return tuple(r_chr[k][:list(r_chr[k]).index(f) + 1])

# display(r_chr.T)

r_df = pd.DataFrame(np.random.randint(0, 100, (10, 10)), tuple(r_chr.b[:10]), tuple(r_chr.s[:10]))

# print_data(r_df)

def run_plt(ak_plt_items):
    ret_items = {}
    for _ in ak_plt_items:
        if isinstance(_, types.FunctionType):
            _()
        if isinstance(_, tuple):
            # (lambda _: plt.gca(), (None,), 'ax') # 获取当前视图 | 回调函数 回调参数(元祖) 返回变量
            _ = list(_) + [None] * 99  # 解决长度过短问题
            a, b, c = _[:3] # 注解需要统一长度 否则过长过短都会报错

            if b is None:
                b = []

            b = list(b)
            b.append(ret_items)

            if isinstance(c, str):
                ret_items.setdefault(c, a(*b))
            else:
                a(*b)

plt_items = [] # 初始化图表数据
#%% md
# 双轴布局
#%% md
## 双轴显示
#%%
# 左右2边都有轴
x = np.linspace(-np.pi, np.pi, 50)
y = np.sin(x)

pd.DataFrame(dict(x=x, sin=y)).round(2).T
#%%
plt.plot(x, y)
_ = plt.yticks(np.linspace(-1, 1, 10+1), color='blue') # 坐标轴蓝色文字、刻度设置 | 进行赋值操作, 使其没有数据打印输出

ax = plt.gca()  # 获取当前视图
ax2 = ax.twinx()  # 把视图复制一份 两个x轴 合到一起 | 不同2个刻度

y2 = np.exp(x) # 自然底数
plt.plot(x, y2, color='red') # 默认向 ax2绘制
_ = plt.yticks(np.arange(0, 25 + 1, 5), color='red') # 设置右边的轴
#%% md
## 文本、注释、箭头
#%%
"""
Pyplot函数 API方法 描述
text() mpl.axes.Axes.text() 在Axes对象的任意位置添加文字
xlabel() mpl.axes.Axes.set_xlabel() 为X轴添加标签
ylabel() mpl.axes.Axes.set_ylabel() 为Y轴添加标签
title() mpl.axes.Axes.set_title() 为Axes对象添加标题
legend() mpl.axes.Axes.legend() 为Axes对象添加图例
annnotate() mpl.axes.Axes.annotate() 为Axes对象添加注释(箭头可选)
figtext() mpl.figure.Figure.text() 在Figure对象的任意位置添加文字
suptitle() mpl.figure.Figure.suptitle() 为Figure对象添加中心化的标题

"""
#%%
# 文本

# 字体属性
font = dict(
    fontsize=20,  # 字体尺寸
    family='STKaiti',  # 字体科族
    color='red',  # 字体颜色
    weight='bold'  # 字体加粗
)

x = np.linspace(0.0, 5.0, 100)
y = np.cos(2 * np.pi * x) * np.exp(-x) # 一个方程

pd.DataFrame(dict(x=x, y=y)).round(2).T
#%%
plt.figure(figsize=(9, 6))  # 调整尺寸
plt.plot(x, y, 'g')  # 绘制图表 线颜色绿色

_ = plt.title('ED', fontdict=font, pad=20) # 设置标题 pad 文本上下距离 | 小标题
_ = plt.suptitle('指数衰减', y=1.05, fontdict=font, fontsize=30) # 大标题 在标题之上
_ = plt.text(x = 2, y=0.65, s= r'$\cos(2 \pi x) * \exp(-x)$', fontsize=25)  # 横纵坐标位置添加文本
_ = plt.text(x = 2, y=0.4, s='Hello!') # 注意引号

_ = plt.xlabel('time (s)')
_ = plt.ylabel('voltage (mV)')

plt.show()
#%% md
## 箭头
#%%
loc = np.random.randint(0, 10, (10, 2))

loc.T
#%%
way = np.arange(10) # 0 ~ 9数字序列
way.reshape(-1, way.shape[0])
#%%
np.random.shuffle(way) # 数据打乱, 修改元数据
way.reshape(-1, way.shape[0])
#%%
plt.figure(figsize=(20, 20))
plt.plot(loc[:,0], loc[:,1], 'g*', ms=20)  # 绘制图 | 第一列 第二列 | 绿色 点星 | 大小 20
plt.grid()  # 网格

for i in range(0, len(way)-1): # 0 ~ (10-1=9) | 0 ~ 9 不包括9
    # print(i)
    a, b, = way[i:i+2]  # 获取 第一个/下一个

    # print(way[i:i+2])
    # print( way[i], way[i+1])

    s = loc[a]  # 第一个
    e = loc[b]  # 下一个

    # print(a, b, s, e)

    # 画线条
    # 上一条线的末尾 会 与下一条先的开始连起来
    plt.arrow(
        s[0], s[1], e[0]-s[0], e[1]-s[1], # 坐标与距离
        head_width=0.2, lw=2, # 箭头长度,箭尾线宽
        length_includes_head = True) # 长度计算包含箭头箭尾

    plt.text(s[0],s[1],s = i,fontsize = 32,color = '#00FFFF') # 文本

    if i == len(way) - 2: # 最后一个点
        plt.text(e[0],e[1],s = i + 1,fontsize = 32,color = '#00FFFF') # 标注 9文本

#%%

#%%

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CY3761

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值