zoukankan      html  css  js  c++  java
  • python:matplotlib

    一,一般步骤:

    • 只包含一个坐标轴

      1. plt.figure()
      2. plt.scatter(),plt.bar(),plt.hist(),plt.pie(),plt.plot()
      3. plt.savefig() 可以保存pdf和png格式
      4. plt.show()
    • 包含多个坐标轴

      1. fig=plt.figure()
      2. ax1=fig.add_subplot(), ax1.hist()
      3. ax2=fig.add_subplot(), ax2.scatter()
      4. ax3=fig.add_subplot(),ax3.plt.pie()
      5. plt.savefig() 可以保存pdf和png格
      6. plt.show()

    示例代码:

    # coding=utf-8
    
    from matplotlib import mpl
    
    import matplotlib.pyplot as plt
    import numpy as np
    
    
    #添上这两句配置,才会显示中文
    mpl.rcParams['axes.unicode_minus']=False
    mpl.rcParams['font.sans-serif']=['SimHei']
    def scatter_test():
        plt.figure(1,figsize=(5, 4))
        plt.scatter(np.random.rand(20), np.random.rand(20))
        plt.title(u'散列图')
        plt.show()
    
    def _test():
        x=np.arange(0,10,0.1)
        y=np.random.randn(len(x))
        plt.figure()#创建一个图形
        plt.plot(x,y)#画图
        plt.title('random numbers')#设置标题
        plt.show()#显示
        
    def bar_test():
        N = 5
        ind = np.arange(N)  # the x locations for the groups
        width = 0.35  # the width of the bars
     
        fig=plt.figure()
        ax=fig.add_subplot(111)#增加一个坐标轴
        menMeans = (20, 35, 30, 35, 27)
        rects1 = ax.bar(ind, menMeans, width, color='r', yerr=0.01)
     
        womenMeans = (25, 32, 34, 20, 25)
        rects2 = ax.bar(ind + width, womenMeans, width, color='y', yerr=0.01)
     
        # add some
        ax.set_ylabel('Scores')
        ax.set_title('Scores by group and gender')
        ax.set_xticks(ind + width)
        ax.set_xticklabels(tuple(np.arange(1,6)))
     
        ax.legend((rects1, rects2), ('Men', 'Women'))
        autolabel(rects1,ax)
        autolabel(rects2,ax)
        plt.show()
        
    def autolabel(rects,ax):
        # attach some text labels
        for rect in rects:
            height = rect.get_height()
            ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height, '%d' % int(height),ha='center', va='bottom')
            
    #一个界面包含多个图       
    def test():
        fig=plt.figure()
        ax1=fig.add_subplot(2,2,1)
        ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3) 
        ax2=fig.add_subplot(2,2,2)
        ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30)) 
        ax3=fig.add_subplot(2,2,3)
        plt.plot([1.5, 3.5, -2, 1.6])
        ax4=fig.add_subplot(2,2,4)
        plt.show()
        
        
    def pie_test():
        labels   = []#标签
        quants   = []#对应的数值
        f=open('data.txt','r')
        # Read data
        for line in f:
            info = line.split()
            labels.append(info[0])
            quants.append(float(info[1]))
    
        for i in range(len(labels)):
            print labels[i],'------->',quants[i]/reduce(lambda x,y:x+y,quants)
            
        # make a square figure
        plt.figure(1, figsize=(6,6))
        
        #是否突出显示
        expl = map(explode,labels)
        # Colors used. Recycle if not enough.
        colors  = ["pink","coral","yellow","orange"]
        # Pie Plot
        # autopct: format of "percent" string;
        plt.pie(quants, explode=expl, colors=colors, labels=labels, autopct='%1.2f%%',pctdistance=0.8, shadow=True)
        plt.title('Top 10 GDP Countries', bbox={'facecolor':'0.8', 'pad':5})
        plt.show()
    
    # For China, make the piece explode a bit
    def explode(label, target='China'):
        if label == target: return 0.1
        else: return 0
        
        
    def bar_test2():
        labels   = []#标签
        quants   = []#对应的数值
        f=open('data.txt','r')
        # Read data
        for line in f:
            info = line.split()
            labels.append(info[0])
            quants.append(float(info[1]))
        
        width=0.4
        ind=np.linspace(0.5, 9.5, 10)
        fig=plt.figure(1, figsize=(12,6))
        ax=fig.add_subplot(111)
        ax.bar(ind-width/2,quants,width,color='r')
        ax.set_ylabel('GDP (Billion US dollar)')
        ax.set_xlabel(u'国家')
        ax.set_title('Top 10 GDP Countries', bbox={'facecolor':'1.0', 'pad':5})
        ax.set_xticks(ind)
        ax.set_xticklabels(labels)
        plt.savefig('test.pdf')
        plt.savefig('picture.png')
        plt.show()
            
    if __name__ == '__main__':
        bar_test2()
  • 相关阅读:
    java实验报告(实验五)
    java实验报告(实验三)
    java读书笔记二
    总结报告
    Android实践项目汇报(总结)-修改
    Android实践项目汇报(总结)
    Android实践项目汇报(四)
    Android实践项目汇报(三)
    Android实践项目汇报(二)
    Android实践项目汇报-改(一)
  • 原文地址:https://www.cnblogs.com/dmir/p/5026245.html
Copyright © 2011-2022 走看看