plt | 子视图

#%%
# CY3761 | 2022-01-18 11:50
#%%
# 此为 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, = _ # 注解需要统一长度 否则过长过短都会报错

            if b is None:
                b = []

            # print(71, _, 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
## 子视图
#%%
# 一个图形当中可以花多种图形
# 数据1
x1 = np.linspace(-np.pi, np.pi, 50)
y1 = np.sin(x1)
y2 = np.cos(x1)

pd.DataFrame({'x':x1, 'sin(x)': y1, 'cos(x)': y2}).round(2).T
#%%
x2 = np.linspace(-np.pi, np.pi, 200)
y3 = np.sin(x2 ** 2)

pd.DataFrame({'x':x2, 'sin(x**2)': y3}).round(2).T
#%%
plt.figure(figsize=(9, 6)) # 调整视图尺寸

# 子视图1
ax = plt.subplot(221)  # 2行2列第1个视图
ax.plot(x1, y1)  # 红色线条

# 子视图2
ax = plt.subplot(2,2,2) # 2行2列第2个视图
ax.plot(x1, y2)
#%%
fig, axes = plt.subplots(2, 2)  # 2r2c 4图 | 和上面不同 带有s

axes[0,0].plot(x1, y1, color='red')  # 红线
axes[0,1].plot(x1, y1, color='green')
axes[1,0].plot(x1, y2, color='purple')
axes[1,1].plot(x1, y2, color='blue')
#%%
plt.figure(figsize=(9,6))
x = np.linspace(-np.pi,np.pi,50)
y = np.sin(x)

# 子视图1
ax = plt.subplot(221) # 两行两列第一个子视图
ax.plot(x,y,color = 'red')
ax.set_facecolor('green') # 调用子视图设置方法,设置子视图整体属性

# 子视图2
ax = plt.subplot(2,2,2) # 两行两列第二个子视图
line, = ax.plot(x,-y) # 返回绘制对象 | 返回的是个列表
line.set_marker('*') # 调用对象设置方法,设置属性
line.set_markerfacecolor('red')
line.set_markeredgecolor('green')
line.set_markersize(10)

# 子视图3
ax = plt.subplot(2,1,2) # 两行一列第二行视图
plt.sca(ax) # 设置当前视图
x = np.linspace(-np.pi,np.pi,200)
plt.plot(x,np.sin(x*x),color = 'red')
#%%
items_a = [1,2,3]
items_b = items_a + [None] * 99
items_c = items_b[:5]  # 保持统一长度
print(items_a, items_b, items_c, sep='\n')
#%% md

#%%
print(3 + 18 / 3 ** 2, 3 + 18 // 3 ** 2)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CY3761

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

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

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

打赏作者

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

抵扣说明:

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

余额充值