python 五matplotlib logging yaml tqdm

1、折线图

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
y1, y2 = np.sin(x), np.cos(x)

plt.plot(x, y1, c='r', ls='-', lw=5)
plt.plot(x, y2, c='#021962', ls='-.', label='y = cos(x)')
plt.legend(loc=2)
plt.xlabel('x - axis')
plt.ylabel('y -axis')

i = 0
for x0, y in zip(x, y1):
    i += 1
    if i % 10 == 0:
        plt.annotate('y=%.2f' % y, xytext=(x0, y), xy=(x0, y))
plt.show()
# plt.savefig(savepath, dpi=600)

 1)np. linspace(0, 2* np.pi, 100) 返回类型是<class 'numpy.ndarray'>,从0到6.28的list。

 2)label=' '和plt. legend()一起使用,用plt.xlabel('y=cos(x)')代替也行。

 3)c='r' 表示①color='red';②还可以#rrggbb; ③(r, g, b) 或 (r, g, b, a)  其中 r g b a 取均为[0, 1]之间。

 4)ls即linestyle表示线的样式,取值  - solid、 --  dashed、 :  dotted、 ''  None、 -.  dashdot。

 5)plt.legend()的loc指位置,取值0 best、 1 upper right、 5 right、 6 center left、 10 center

 6)线结点的样式

 关键字 mec  markeredgecolor、 mew  markeredgewidth、 mfc  markerfacecolor、 mfcalt  markerfacecoloralt 、 ms  markersize

 关键字取值:https://www.cnblogs.com/onemorepoint/p/7482644.html  试试:

plt.plot(x, y1, marker='o', mec='r', mfc='g',ms=20,mew=5)
plt.plot(x, y2, marker='*', ms=8)
plt.xlabel("i am x_label")

2、柱状图

import matplotlib.pyplot as plt
import matplotlib               # 引入

matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 中文设置

x_label = ['2014', '2015', '2016', '2017']    
bar_heights = [20, 30, 15, 35]                        
rects = plt.bar(range(len(bar_heights)), height=bar_heights, width=0.9,  alpha=0.8, color='red', label="一部门")

plt.ylim(0, 50)                 
plt.ylabel("数量")
plt.title("某某公司")

plt.xticks(range(len(bar_heights)), x_label)
plt.show()                      # 显示 

 1)每一条柱占据一个单位宽,但显示的位置与宽度由plt. bar决定。

 2)range(len(bar_heights))即[0, 1, 2, 3],表示每一个条柱左下端点的位置,右下端点的位置需要在根据width得出。

 3)plt.xticks例子中[0, 1, 2, 3],但x_label显示在0.5, 1.5, 2.5, 3.5刻度处。

 4)plt. ylim(0, 50)表示y轴的取值范围。

for rect in rects:        # 在每个条柱上标明
    height = rect.get_height()
    plt.text(rect.get_x() + rect.get_width() / 2, height+1, str(height), ha="center", va="bottom")

 

3、散点图 参见https://www.cnblogs.com/sunshinewang/p/6853813.html 

import numpy as np
import matplotlib.pyplot as plt
N = 1000
x = np.random.randn(N)
y = np.random.randn(N)
plt.scatter(x, y)
plt.show()

  scatter() 函数主要参数
  scatter(x, y, s=None, c=None, marker=None, edgecolors=None, alpha=None, linewidths=None)

 1) s即size,点的大小面积,默认是20

 2) c即color,点的颜色,默认蓝色

 3) mark 点的形状,默认是圆 

plt.rcParams['font.sans-serif']=['SimHei']      # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False        # 用来正常显示负号 

4、饼状图 参见https://www.cnblogs.com/zsr0401/p/6405538.html

import matplotlib.pyplot as plt

labels = 'A', 'B', 'C', 'D'
datas = [15, 30.55, 44.44, 10]
explode = [0, 0.1, 0, 0]      # 0.1 凸出这部分,
plt.axes(aspect=1)        # set this , Figure is round, otherwise it is an ellipse

plt.pie(x=datas, labels=labels, explode=explode, autopct='%3.1f %%',
        shadow=True, labeldistance=1.1, startangle=90, pctdistance=0.6 )
plt.show()
labeldistance      文本的位置离远点有多远,1.1指1.1倍半径的位置
autopct    圆里面的文本格式,%3.1f%%表示小数有三位,整数有一位的浮点数
shadow    饼是否有阴影
startangle    起始角度,0,表示从0开始逆时针转,为第一块。一般选择从90度开始比较好看
pctdistance   百分比的text离圆心的距离
patches, l_texts, p_texts 为了得到饼图的返回值,p_texts饼图内部文本的,l_texts饼图外label的文本

5、绘制热力图

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
               # 初始化二维数组
p.random.seed(1)
data = np.random.rand(12, 12)

sns.set()
ax = sns.heatmap(data,cmap="Purples", center=0)  #"YlGnBu"
plt.show() 

 

 二、logging

1、相当于功能复杂点的print

import logging  
logging.basicConfig(level=logging.NOTSET) 
# 将信息打印到控制台上
logging.debug(u"同志们")
logging.info(u"中华人民共和国")
logging.warning(u"中央人民政府")
logging.error(u"在今天")
logging.critical(u"成立了")

  级别有critical > error > warning > info > debug,默认info和debug都是不会输出信息到控制台的。

设置了logging.basicConfig(level=logging.NOTSET, format=)就能输出info和debug的信息了。若设置level=logging.info效果与默认相同。

2、日志输出-文件

  创建logging、创建handler、将logger添加进handler

import logging
import os.path
import time
# 第一步,创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)  # Log等级总开关

# 第二步,创建一个handler,用于写入日志文件
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
log_filename = os.path.join(os.path.dirname(os.getcwd()), rq + '.log')

fh = logging.FileHandler(log_filename, mode='w')
fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
# 第三步,定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)

# 第四步,将logger添加到handler里面
logger.addHandler(fh)
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')

3、输出格式format

%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息

捕捉异常

try:
    open('/path/to/does/not/exist', 'rb')
except (SystemExit, KeyboardInterrupt):
    raise
except Exception, e:
    logger.error('Failed to open file', exc_info=True)

  

  三、yaml

 https://blog.csdn.net/weixin_38924500/article/details/112613734

# ***获取yaml文件数据***
usr01:
  name: 张三
  psw: 123
usr02:
  name: 李四
  psw: 3.1415

# yaml键值对中嵌套数组
usr3:
   - a
   - "shine 20034"
   - 2018-03-01t11:33:22.55-06:00
   - 2019-01-10
   - true
   - null
usr4:
   - b
test.yaml

  .yaml书写格式:

  键值对key: value、或key:list

  用若干个空格缩进,而非tab键;保证相同层级空格数一致 即左对齐即可。

  自动识别value的类型,字符串可不加""双引号

四、tqdm可视化

from tqdm import tqdm

 

2020-03-04 21:51:46

posted @ 2020-03-04 21:52  shines87  阅读(449)  评论(0)    收藏  举报