zoukankan      html  css  js  c++  java
  • Matplotlib 绘图与可视化 一些属性和错误

    属性

    *)在使用animate方法中若让interval=0,则会直接输出最后一帧

    *)清除图像  包括这个方法到底是图形区的对象调用的还是画布对象调用的?

      这个莫名其妙就起作用了

      来源连接:https://codeday.me/bug/20170309/5150.html

    def update_insert(i):
        global ax,X
        plt.cla()#要以绘图区的对象调用的方法吧
        # plt.close()#这里又能关闭了
        # plt.clf()#清楚figure里的内容
        X=np.random.randint(0,100,10)
        ax.scatter(X,X)
        plt.xticks([]),plt.yticks([])
        return ax,X

     

     *)调整图像边缘及图像间的空白间隔plt.subplots.adjust(6个参数)

      图像外部边缘的调整可以使用plt.tight_layout()进行自动控制,此方法不能够很好的控制图像间的间隔.如果想同时控制图像外侧边缘以及图像间的空白区域,使用命令:

    plt.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.8,hspace=0.2, wspace=0.3)
    

      *)subplot(111)参数为111,即中间没有逗号隔开的意思。

      参考链接:https://blog.csdn.net/S201402023/article/details/51536687

      

     #引入对应的库函数
    import matplotlib.pyplot as plt
    from numpy import *
    
    #绘图
    fig = plt.figure()
    ax = fig.add_subplot(349)
    ax.plot(x,y)
    plt.show()
    

      其中,参数349的意思是:将画布分割成3行4列,图像画在从左到右从上到下的第9块

      那第十块怎么办,3410是不行的,可以用另一种方式(3,4,10)。

      如果一块画布中要显示多个图怎么处理?

    import matplotlib.pyplot as plt
    from numpy import *
    
    fig = plt.figure()
    ax = fig.add_subplot(2,1,1)
    ax.plot(x,y)
    ax = fig.add_subplot(2,2,3)
    ax.plot(x,y)
    plt.show()
    

      

    错误

    *)c:usersadministrator.sc-201605202132appdatalocalprogramspythonpython36Lib kinter\__init__.py:1705: UserWarning: Tight layout not applied. The left and right margins cannot be made large enough to accommodate all axes decorations.

    axs=fig.add_subplot(111)
    axs.set_xlim(0,7)
    axs.set_ylim(0,5)
    text= axs.text(0.02,0.90,'test',transform=axs.transAxes)
    text.set_backgroundcolor('r')
    text.set_position((0.9,.9))#不能超过1,和上面的设置是一样的
    

      

    *)matplotlib.units.ConversionError: Failed to convert value(s) to axis units: ['bubble_sort', 'bidirectional_bubble_sort']

    xticks=[d.__name__ for d in algorithm_list]
    print(xticks)
    axs.set_xticks(xticks)#因为是字符串数组,所以不能,应该是数字
    #xticks
    ['bubble_sort', 'bidirectional_bubble_sort']

      

    *)ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

    #错误的
    spend_time=[1,2]
    axs.set_yticks([spend_time])
    #True
     axs.set_yticks(spend_time)
    

      

    *)axs[i].set_xticks([])   TypeError: 'list' object is not callable


    参考链接:https://stackoverflow.com/questions/46231439/problems-with-matplotlib-pyplot-xticks(见回答2)

      原因:是因为起那面已经有过设置x轴标记为空的了

    for i in range(algorithm_num):
            frames_names[algorithm_list[i].__name__]=[]
            #顺便对画布进行设置
            axs.append(fig.add_subplot(121+i))
            # axs[-1].set_xticks=([])#这里已经有过了,将这个注释掉
            # axs[-1].set_yticks=([])
            #顺便运行函数了
            frames_names[algorithm_list[i].__name__]=algorithm_list[i](copy.deepcopy(original_data_object))
        plt.subplots_adjust(left=0.05,right=0.95,bottom=0.1,top=0.90,wspace=0.1,hspace=0.2)
    
        #寻找最大帧,算了,还是把所有的帧数都存到一个dict里面吧,但是dict好像不能向里面添加
        frame_count={}
        for i in range(algorithm_num):
            frame_count['{}'.format(algorithm_list[i])]=str(len(frames_names[algorithm_list[i].__name__]))
        def animate(fi):
            bars=[]
            for i in range(algorithm_num):
                if len(frames_names[algorithm_list[i].__name__])>fi:
                    axs[i].cla()
                    
                    axs[i].set_xticks([])
                    axs[i].set_yticks([])
                    axs[i].set_title(str(algorithm_list[i].__name__))
                    bars+=axs[i].bar(list(range(Data.data_count)),
                                 [d.value for d in frames_names[algorithm_list[i].__name__][fi]],
                                 1,
                                 color=[d.color for d in frames_names[algorithm_list[i].__name__][fi]],
                                 ).get_children()
            return bars
    

      

    *)funcAnimation()中frags向帧函数传递附加参数时格式不对提示错误TypeError: update_insert() takes 2 positional arguments but 10 were given

    正确格式:

    anim=animation.FuncAnimation(plt.fig,update_insert,init_func=None,repeat=False,frames=np.arange(0,6 ),interval=2000,fargs=(collection))
    
    def update_insert(i,*collection):
        global ax,X
        print(collection) 
        --snip--
    

      

    *)由于scatter()中参数不规范引起的错误

    参考链接:https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.scatter.html?highlight=scatter#matplotlib.pyplot.scatter

    标记颜色。可能的值:

    • 单色格式字符串。
    • 一系列长度为n的颜色规格。
    • 使用cmap和 norm映射到颜色的n个数字序列
    • 一个二维数组,其中行是RGB或RGBA。

    请注意,c不应该是单个数字RGB或RGBA序列,因为它与要进行颜色映射的值数组无法区分。如果要为所有点指定相同的RGB或RGBA值,请使用具有单行的二维数组。否则,在大小与x 和y匹配的情况下,值匹配将具有优先权

    默认为None在这种情况下,标记的颜色是由的值来确定colorfacecolorfacecolors如果未指定或None标记颜色,则标记颜色由Axes“当前”形状的下一个颜色确定并填充“颜色循环”。此周期默认为rcParams["axes.prop_cycle"]

            ax.scatter(X1,X1,c=b)
            ax.scatter(X2,X2,c=b,s=50)
            ax.scatter(X1,X1,c=g)
    

      会报错:

    (sort) λ python matplotlib_learn.py
    [1, 2, 3, 4, 5]
    Traceback (most recent call last):
      File "C:UsersAdministrator.SC-201605202132Envssortlibsite-packagesmatplotlibcbook\__init__.py", line 216, in process
        func(*args, **kwargs)
      File "C:UsersAdministrator.SC-201605202132Envssortlibsite-packagesmatplotlibanimation.py", line 953, in _start
        self._init_draw()
      File "C:UsersAdministrator.SC-201605202132Envssortlibsite-packagesmatplotlibanimation.py", line 1732, in _init_draw
        self._draw_frame(next(self.new_frame_seq()))
      File "C:UsersAdministrator.SC-201605202132Envssortlibsite-packagesmatplotlibanimation.py", line 1755, in _draw_frame
        self._drawn_artists = self._func(framedata, *self._args)
      File "matplotlib_learn.py", line 184, in update_insert
        ax.scatter(X2,X2,c=b,s=50)
      File "C:UsersAdministrator.SC-201605202132Envssortlibsite-packagesmatplotlib\__init__.py", line 1589, in inner
        return func(ax, *map(sanitize_sequence, args), **kwargs)
      File "C:UsersAdministrator.SC-201605202132Envssortlibsite-packagesmatplotlibaxes\_axes.py", line 4446, in scatter
        get_next_color_func=self._get_patches_for_fill.get_next_color)
      File "C:UsersAdministrator.SC-201605202132Envssortlibsite-packagesmatplotlibaxes\_axes.py", line 4257, in _parse_scatter_color_args
        n_elem = c_array.shape[0]
    IndexError: tuple index out of range
    

      *)ValueError: shape mismatch: objects cannot be broadcast to a single shape错误:

      可能是因为传入的两个参数之间不是一一对应的,类似于因为长度的原因,一个参数中的某些数据不能和另一个参数中的数据一起被使用。比如在画图的时候

    bars+=ax.bar(list(range(0,Data.data_count)),#我在创建数据的时候搞错了,这里是16个,而下面的是17个
                            [d.value for d in frames[fi]],
                            1,
                            color=[d.color for d in frames[fi]]
                            ).get_children()
    

      *)类中的类似变量名错误的错误不会提示啊,哦哦好像是别的地方就写错了

    def set_color(self,ragb=None):#这里也写错了
    if not ragb:#这里也写错了 rgba=(0,#但是这个这么没有提示 1-self.value/(self.data_count*2), self.value/(self.data_count*2)+0.5, 1) self.color=ragb ---snip--- d=Data(2) print(d.color) #输出 (sort) λ python Visualization_bubble_sort.py None

      

      

  • 相关阅读:
    色彩空间RGB/CMYK/HSL/HSB/HSV/Lab/YUV基础理论及转换方法:RGB与YUV
    三色视者与四色视者身后的理论基础:色彩原理
    再谈设计原则—7种设计原则学习总结笔记
    sass安装:webpack sass编译失败,node-sass安装失败的终极解决方
    再谈Java数据结构—分析底层实现与应用注意事项
    再谈js对象数据结构底层实现原理-object array map set
    浮点数精度问题透析:小数计算不准确+浮点数精度丢失根源
    再谈编程范式—程序语言背后的思想
    再谈循环&迭代&回溯&递归&递推这些基本概念
    再谈MV*(MVVM MVP MVC)模式的设计原理—封装与解耦
  • 原文地址:https://www.cnblogs.com/Gaoqiking/p/11075384.html
Copyright © 2011-2022 走看看