#%%
# CY3761 | 2022-01-14 12:16
#%%
# 此为 jupyter 模版, 执行 build 后记住先执行-全部运行
# 使用 DataSpell 进行编写文档
# 变量名、函数名小写分段处理
#%%
# 导入项
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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)
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)
#%% md
# Matplotlib概述
#%% md
+ pip install matplotlib
#%% md
## 图形绘制
#%%
"""
@_copy_docstring_and_deprecators(Axes.plot)
def plot(
*args: Any,
scalex: bool = True,
scaley: bool = True,
data: Any = None,
**kwargs: Any) -> Any
x = np.arange(0, 5, 0.1) # 横坐标
y = np.sin(x) # 纵坐标
plt.plot(x, y)
Plot y versus x as lines and/or markers.
Call signatures::
plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
"""
x = np.linspace(0, 2 * np.pi, 100) # 等差数列 0 ~ 360' 分 100 份 | numpy.array
y = np.sin(x) # 正弦波 | 所有数据都进行正弦操作
plt.plot(x, y)
#%%
plt.xlim(-1, 10) # x坐标
plt.ylim(-1.5, 1.5) # y坐标
# linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
plt.grid(color='green', alpha=0.5, linestyle='-.') # 网格线 | 网格线颜色 color | alpha 透明度 | linestyle 网格线样式 (--虚线) (-实线[默认])
plt.plot(x, y)
#%%
plt.xlim(-1, 10) # x坐标
plt.ylim(-1.5, 1.5) # y坐标
# ValueError: '_.' is not a valid value for ls; supported values are '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
# '-' 'solid' | '--' 'dashed' | '-.' 'dashdot' | ':' 'dotted'
# 'None', ' ', '' 都是无网格线
plt.grid(color='green', alpha=0.5, linestyle=' ') # 网格线 | 网格线颜色 color | alpha 透明度 | linestyle 网格线样式 (--虚线) (-实线[默认]) 空表示无网格线
plt.plot(x, y)
#%%
plt.xlim(-1, 10) # x坐标
plt.ylim(-1.5, 1.5) # y坐标
plt.grid(color='green', alpha=0.5, linestyle=':', linewidth=5) # 网格线 | 网格线颜色 color | alpha 透明度 | linestyle 网格线样式 | linewidth 网格线宽度 (多清晰的网格)
plt.plot(x, y)
#%% md
## 坐标轴可读、标签、标题
#%%
# 找到系统有那些字体
from matplotlib import font_manager # 管理字体
fm = font_manager.FontManager()
np.array([font.name for font in fm.ttflist]) # 字体名字
#%%
# 设置全局参数
# 注意在编辑器是无法对中括号中的键值进行代码提示 需要使用浏览器才能代码提示
plt.rcParams['font.family'] = plt.rcParams['font.sans-serif'] = 'SimHei' # 设置字体 国标黑体中文字体
plt.rcParams['axes.unicode_minus'] = False # 设置正常显示符号
plt.rcParams['font.size'] = 18 # 设置字体尺寸(所有字体)
plt.figure(figsize=(64,9)) # 设置图表大小 单位英寸
plt.title('Sin(x) 正弦波', fontsize=18, color='red', pad=20) # 标题 | fontsize 字体大小 | color 字体颜色 | pad 文字间距 | 标题中文会有问题(需要设置字体)
# 设置标签
plt.xlabel('X')
plt.ylabel('f(x)=sin(x)', rotation=0, horizontalalignment='right') # rotation=0 文字水平显示 | horizontalalignment 水平对齐方式
# 设置刻度
plt.yticks([-1,0,1]) # 数字变了
plt.xticks(np.arange(0, 7)) # 数字再大也没用
arange = np.arange(0, 7, step=0.1)
plt.xticks(
[_ * np.pi for _ in arange], # 刻度
[str(_.round(2)) + '$\pi$(%s)' % (_ * np.pi).round(2) for _ in arange], # 显示
color='red' # 颜色
)
plt.plot(x, y) # 画图
#%% md
+ 分数+pi显示 pi/2
### $\frac{\pi}{2}$ $\pi$
#%%
plt | Matplotlib概述
最新推荐文章于 2022-12-03 16:37:03 发布