• 数据分析(3)-matplotlib基础


    1.安装

    安装visual环境:https://visualstudio.microsoft.com/downloads/

    安装numpy:pip install numpy

    安装matplotlib:pip install matplotlib

    2.基本使用(折线图)

    import matplotlib.pyplot as plt
    import numpy as np
    
    # 查看windows下的字体:C:WindowsFonts
    import matplotlib.font_manager as fm
    
    # 导入并设置中文字体,将字体旋转45度
    myfont = fm.FontProperties(fname=r'C:WindowsFontssimsun.ttc')
    
    # 绘制正方形边长与周长关系变化图
    # 定义x,范围是(-3,3),个数是50
    x = np.linspace(-3, 3, 50)
    y1 = 2*x + 1
    y2 = x**2
    
    # 定义图像窗口figure 2,figsize表示图像窗口大小,dpi图像窗口像素
    fig = plt.figure(num=2, figsize=(8, 8), dpi=60)
    
    # 画(x,y)曲线,color表示曲线颜色,alpha表示折线透明度(0-1),linestyle表示曲线样式,linewidth表示曲线宽度,marker表示曲线折点样式
    l1 = plt.plot(x, y1, color='blue',alpha=0.5,linestyle='--',linewidth=2,marker='',label='y1')
    l2 = plt.plot(x, y2, color='black',alpha=0.5,linestyle='-',linewidth=2,marker='',label='y2')
    
    # 设置标题
    plt.title('实验图', fontproperties=myfont, color='black', size=16)
    
    # xlabel、ylabel分别拟定x、y轴名称,fontproperties指定字体,size设置字体大小,rotation设置字体角度
    plt.xlabel('x轴', fontproperties=myfont, rotation=0, size=12)
    plt.ylabel('y轴', fontproperties=myfont, size=12)
    
    # 分别设置x、y轴范围
    plt.xlim((-1, 2))
    plt.ylim((-2, 3))
    
    # 设置坐标轴刻度及名称
    tick = np.linspace(-1, 2, 5)
    plt.xticks(tick)
    plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really bad$', r'$bad$', r'$normal$', r'$good$', r'$really good$'])
    
    # 获取当前坐标轴信息
    ax = plt.gca()
    
    # ---------设置图像边框及颜色--------------------
    # .spines设置边框,.set_color设置边框颜色
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    
    # ----------调整刻度及边框位置--------------------
    # .xaxis.set_ticks_position设置x坐标刻度数字或名称的位置
    # .spines设置边框:x轴,.set_position设置边框位置:y=0位置
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data', 0))
    
    # .yaxis.set_ticks_position设置y坐标刻度数字或名称的位置
    # .spines设置边框:y轴,.set_position设置边框位置:x=0位置
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('data',0))
    
    # 对[x0,y0]进行标注
    plt.scatter([x[10], ], [y1[10], ], s=50, color='b')
    
    # 设置图例及位置
    plt.legend(loc='best')
    #plt.legend(handles=[l1,l2,], labels=['yl_line','y2_line'], loc='best')
    
    # 显示图像
    plt.show()

    3.参考资料

    1)科赛:https://www.kesci.com/home/project/5de9f0a0953ca8002c95d2a9

    2)官网:https://matplotlib.org/gallery/index.html#lines-bars-and-markers

    3)天池:https://tianchi.aliyun.com/notebook-ai/detail?spm=5176.12282042.0.0.68792042BNUzC2&postId=23636

    df = pd.DataFrame(np.random.rand(10,2),columns=['A','B'])
    
    # 创建图表窗口,设置窗口大小
    # 创建图表对象,并赋值与fig
    fig = df.plot(figsize=(6,4))
    
    # 图名
    plt.titile('')
    
    # x轴标签
    # y轴标签
    plt.xlabel('')
    plt.ylabel('')
    
    # 显示图例,loc表示位置
    plt.legend(loc='')
    
    # x轴边界
    # y轴边界
    plt.xlim([0,12])
    plt.ylim([0,1.5])
    
    # 设置x刻度
    # 设置y刻度
    plt.xticks(range(10))
    plt.yticks([0,0.2,0.4,0.6,1.0,1.2])
    
    # 设置x轴刻度标签
    # 设置y轴刻度标签
    fig.set_xticklabels("% lf" %i for i in range(10))
    fig.set_yticklabels("% 2f" %i for i in [0,0.2,0.4,0.6,1.0,1.2])
    
    # 显示网格
    # linestyle:线型
    # color:颜色
    # linewidth:宽度
    # axis:x,y,both,显示x、y、两者的格网
    plt.grid(True, linestyle='', color='', linewidth='', axis='')
    
    # 刻度显示
    plt.tick_params(bottom='on', top='off', left='on', right='off')
    
    # 刻度显示方向,in, out, inout
    # 需要导入matplotlib,不仅是matplotlib.pyplot
    matplotlib.reParams['xtick_direction'] = 'out'
    matplotlib.reParams['ytick_direction'] = 'inout'
    
    # 关闭坐标轴
    frame=plt.gca()
    
    # x轴不可见
    # y轴不可见
    frame.axes.get_xaxis().set_visible(False)
    frame.axes.get_yaxis().set_visible(False)
    
    图表样式参数
    linestyle,线样式
    marker,点样式
    color,线颜色
    alpha,透明度
    colormap,颜色板,渐变色
    style,包含:linestyle、marker、color
    
    风格:自动配色,调样式
    import matplotlib style as psl
    psl.available
    psl.use('')
    
    
    
    刻度、注解、图表输出
    from matplotlib.ticker import MultipleLocator,FormatStrFormatter
    
    # 将主刻度标签设置为10的倍数
    xmajorLocator = MultipleLocator(20)
    
    # 设置x轴标签文本的格式
    xmajorFormatter = FormatStrFormatter('%.0f')
    
    # 将x轴此刻度标签设置为5的倍数
    xminorLocator = MultipleLocator(5)
    
    # 将y轴主刻度标签设置为0.5的倍数
    ymajorLocator = MultipleLocator(0.5)
    
    # 设置y轴标签文本的格式
    ymajorFormatter = FormatStrFormatter('%.1f')
    
    # 将y轴此刻度标签设置为0.1的倍数
    yminorLocator = MultipleLocator(0.1)
    
    # 设置x轴主刻度
    ax.xaxis.set_major_locator(xmajorLocator)
    
    # 设置x轴标签文本格式
    ax.xaxis.set_major_formatter(xmajorFormatter)
    
    # 设置x轴次刻度
    ax.xaxis.set_minor_locator(xinorLocator)
    
    # 设置y轴主刻度
    ax.yaxis.set_major_locator(ymajorLocator)
    
    # 设置y轴标签文本格式
    ax.yaxis.set_major_formatter(ymajorFormatter)
    
    # 设置y轴次刻度
    ax.yaxis.set_minor_locator(yminorLocator)
    
    # which 格网显示
    # x坐标轴的网格使用主刻度
    # y坐标轴的网格使用次刻度
    ax.xaxis.grid(True,which='majpr')
    ax.yaxis.grid(True,which='minor')
    
    # 删除坐标轴的刻度显示
    ax.yaxis.set_major_locator(plt.NullLocator())
    ax.xaxis.set_major_formatter(plt.NullFormatter())
    
    注解
    plt.text(5,0.5,'最大值',fontsize=10)
    
    
    子图创建方法1
    fig = plt.figure(figsize=(10,6),facecolor='gray')
    
    ax1 = fig.add_subplot(2,2,1)
    plt.plot(np.random.rand(50).cumsum(),'k--')
    plt.plot(np.random.randn(50).cumsum(),'b--')
    
    ax2.fig.add_subplot(2,2,2)
    ax2.hist(np.random.rand(50),alpha=0.5)
    
    ax3 = fig.add_subplot(2,2,3)
    df3 = pd.DataFrame(np.random.rand(10,4),columns=['a','b','c','d'])
    ax4.plot(df3,alpha=0.5,linestyle='--',marker=' ')
    
    子图创建方法2
    fig.axes = plt.subplots(2,3,figsize=(10,4))
    ts = pd.Series(np.random.randn(1000),cumsum())
    
    ax1 = axes[0,1]
    ax1.plot(ts)
    
    # sharex,sharey:是否共享x,y刻度
    fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
    
    for i in range(2):
    	for j in range(2):
    		axes[i,j].hist(np.random.randn(500),color='k',alpha=0.5)
    
    # wspace、hspace:用于控制宽度和高度高分比,如subplot间距
    plt.subplots_adjust(wspace=0,hspace=0)
    

      

     

     

  • 相关阅读:
    手机端阻止页面滑动-模板
    window.location各个属性-笔记
    面向对象的编程思想
    异步执行原理
    移动端rem布局实现(vw)
    用css3实现摩天轮旋转的动画效果
    js如何从一个数组中随机取出n个不同且不重复的值
    js数组中如何去除重复值?
    各大主流流浪器的内核是什么?
    javascript数组常用方法
  • 原文地址:https://www.cnblogs.com/Iceredtea/p/12048684.html
Copyright © 2020-2023  润新知