美文网首页数据分析
python下matplotlib 绘图入门

python下matplotlib 绘图入门

作者: 任海亮 | 来源:发表于2016-09-06 00:21 被阅读0次

    matplotlib

    本文是在ipython notebook上编写,是matplot的学习笔记

    对一些常用的图形做一些简单的介绍
    包括线图,柱状图,饼图等
    作图我还是服ggplot,蛤蛤
    In [18]:
    直接写代码,先导入相关包

    import matplotlib.pyplot as plt #导入matplotlib库
    import random
    random.seed(111)
    import numpy as np
    %matplotlib inline
    

    In [2]:

    first plot 第一个简单的图,随便写些数据

    x= [1,2,3]
    y=[4,5,2]
    x2=[1,2,3]
    y2=[10,12,11]
    plt.plot(x,y,label="first line")
    plt.plot(x2,y2,label="senond")
    plt.xlabel("plot num")
    plt.ylabel("variance")
    plt.title("first graph")
    plt.legend()
    

    Out[2]:
    <matplotlib.legend.Legend at 0x7a7a2d0>

    In [3]:

    bar plot 柱状图

    x3= [2,4,6,8,10]
    y3=[6,7,5,7,6]
    x4=[1,3,5,7,9]
    y4=[3,4,7,8,5]
    plt.bar(x3,y3,label="first",color="red")
    plt.bar(x4,y4,label="senond")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("first\n graph")
    plt.legend()
    

    Out[3]:
    <matplotlib.legend.Legend at 0x7bc4830>

    In [4]:

    histgram 直方图

    population_ages=[25,44,7,11,16,49,33,54,43,22,77,54,33,52,39,44,50,76,88,67,90,72]
    bins=[0,10,20,30,40,50,60,70,80,90,100]
    plt.hist(population_ages,bins,histtype="bar",rwidth=0.8,alpha=0.4)#rwidth宽度,alpha透明度
    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("age distribution")
    plt.legend()
    

    C:\Anaconda3\lib\site-packages\matplotlib\axes_axes.py:519: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots. warnings.warn("No labelled objects found. "

    In [5]:

    散点图sactter

    x5= [1,2,3,5,3,8]
    y5=[4,5,2,7,6,5]
    plt.scatter(x5,y5,label="first",color="g",s=50,marker="*")
    ​
    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("graph")
    plt.legend()
    

    Out[5]:
    <matplotlib.legend.Legend at 0xa02cc90>

    In [6]:

    堆积图stackplot

    days=[1,2,3,4,5]
    sleeping=[7,8,6,10,7]
    eating=[2,3,4,1,2]
    working=[9,8,10,11,8]
    playing=[6,5,4,2,7]
    stackplot不能加Label,但我们可以用其他方法
    plt.plot([],[],color="g",label="sleeping",linewidth=5)
    plt.plot([],[],color="b",label="eating",linewidth=5)
    plt.plot([],[],color="r",label="working",linewidth=5)
    plt.plot([],[],color="y",label="playing",linewidth=5)
    plt.stackplot(days,sleeping,eating,working,playing,colors=["g","b","r","y"])
    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("graph")
    plt.legend()
    

    Out[6]:
    <matplotlib.legend.Legend at 0xa038f50>

    In [7]:

    饼图pie plot

    slices=[7,3,10,5]
    activities=["sleeping","eating","working","playing"]
    cols=["g","b","r","y"]
    plt.pie(slices,labels=activities,colors=cols,startangle=90,labeldistance=1.1,radius=1.2,
     autopct="%1.1f%%" ,explode=(0,0.2,0,0),shadow=True)
    

    注意:startangle 角度90,labeldistance label到中心距离,radius图形大小,autopct显示百分比

    Out[7]:
    ([<matplotlib.patches.Wedge at 0xa0bef70>, <matplotlib.patches.Wedge at 0xa0c4e30>, <matplotlib.patches.Wedge at 0xa0c9cd0>, <matplotlib.patches.Wedge at 0xa0ceb70>], [<matplotlib.text.Text at 0xa0c47d0>, <matplotlib.text.Text at 0xa0c9670>, <matplotlib.text.Text at 0xa0ce510>, <matplotlib.text.Text at 0xa0d53b0>], [<matplotlib.text.Text at 0xa0c4b10>, <matplotlib.text.Text at 0xa0c99b0>, <matplotlib.text.Text at 0xa0ce850>, <matplotlib.text.Text at 0xa0d56f0>])

    其他参数:

    ax1.grid(True,color="g",linestyle="-",linewidth=5) #网格线和参数  
    plt.subplot_adjust(left=,right,bottom,top,wspace)# 图形距上下左右距离
    

    In [9]:

    subplot 在一个图里创建多个子图

    import random

    想要不同的图片风格,下面这条语句一定要记得

    from matplotlib import style
    style.use("ggplot")
    

    可以使用不同的style,如著名的fivethirtyeight,还有ggplot,查看style.library,还可以自定义style。吼啊!

    https://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html

    fig=plt.figure()
    def create_plot():
     xs =[]
     ys = []
     for i in range(10):
     x=i
     y=random.randrange(10)
     xs.append(x)
     ys.append(y)
     return xs,ys
    ax1 = fig.add_subplot(211) #subplot ,2高1宽1第几个
    ax2 = fig.add_subplot(212)
    

    如果想要上面两个,下面一个,共三个图形,可以

    ax1(221),ax2(222),ax3(212)
    x,y=create_plot()
    ax1.plot(x,y)
    x,y=create_plot()
    ax2.plot(x,y)
    


    Out[9]:
    [<matplotlib.lines.Line2D at 0x4ab8b50>]

    In [10]:

    另一种subplot方法

    ax3=plt.subplot2grid((6,1),(0,0),rowspan=1,colspan=1)
    ax4=plt.subplot2grid((6,1),(1,0),rowspan=4,colspan=1)#还可以
    sharex=ax3
    ax5=plt.subplot2grid((6,1),(5,0),rowspan=1,colspan=1)
    x,y=create_plot()
    ax3.plot(x,y)
    x,y=create_plot()
    ax4.plot(x,y)
    x,y=create_plot()
    ax5.plot(x,y)
    

    Out[10]:
    [<matplotlib.lines.Line2D at 0x4b3cf10>]

    In [15]:

    fill_between 填充颜色到曲线中

    from matplotlib import style
    style.use("fivethirtyeight")#换个非常著名的fivethirtyeight
    a=np.random.randn(100).cumsum()+50
    b=np.random.randn(100).cumsum()+50
    c=range(100)
    fig=plt.figure()
    ax6 = fig.add_subplot(211)
    ax7 =fig.add_subplot(212)
    ax6.plot(c,a)
    ax6.plot(c,b)
    ax6.fill_between(c,a,b,where=(a<b),facecolor='y',edgecolor='k',alpha=0.5)
    ax6.fill_between(c,a,b,where=(a>b),facecolor='b',edgecolor='k',alpha=0.5)
    ax7.plot(c,a-b)
    #这样看起来更清楚了
    

    Out[15]:
    [<matplotlib.lines.Line2D at 0x4eb2410>]

    In [20]:

    3d plot 3D绘图

    from mpl_toolkits.mplot3d import axes3d
    fig=plt.figure()
    ax01 = fig.add_subplot(111,projection = "3d")
    x = [1,2,3,4,5,6,7,8,9]
    y = [4,3,5,6,2,5,7,6,3]
    z = [4,6,7,3,7,4,8,5,4]
    ax01.plot_wireframe(x,y,z)
    ax01.set_xlabel("x label")
    ax01.set_ylabel("y label")
    ax01.set_zlabel("x label")
    

    Out[20]:
    <matplotlib.text.Text at 0xa1bb8d0>

    还有basemap,暂时不做了 matplotlib里面还有很多toolkit,比如seaborn http://matplotlib.org/mpl_toolkits/index.html?highlight=basemap 想找自己喜欢的colors可以到官网 named_colors
    matplotlib 2.0 有个新的更好的colormap "viridis",原来的默认colormap真心不漂亮
    以上! 只是做了一点微小的工作

    相关文章

      网友评论

        本文标题:python下matplotlib 绘图入门

        本文链接:https://www.haomeiwen.com/subject/ifcdettx.html