【问题标题】:Warning " Adding an axes using the same arguments" and custom plot function警告“使用相同的参数添加轴”和自定义绘图功能
【发布时间】:2019-08-06 18:00:00
【问题描述】:

我制作了一个函数,可以让直方图按照我喜欢的方式绘制(带有误差线!)。

def histoPlot(h,fmt='.',lighter_error=0.75,**kwargs):
#fig, ax = plt.subplots(1)
ax = plt.axes()
# Get the current color in the cycle     #https://stackoverflow.com/questions/28779559/how-to-set-same-color-for-markers-and-lines-in-a-matplotlib-plot-loop

color = next(ax._get_lines.prop_cycler)['color']
if all(h.uncertainties != None):
    # plot the error bar https://matplotlib.org/gallery/statistics/errorbar_features.html?highlight=error%20plot
    ax.errorbar(u.midpoints(h.bins), h.counts, yerr=h.uncertainties,color = lighten_color(color,lighter_error),fmt=fmt )
# plot the histogram
ax.step(h.bins,np.append(h.counts,h.counts[-1:]),where='post',color=color,**kwargs)

这对我来说是完美的,我可以用它来用简单的线条制作复杂的情节

histoPlot(histo1,fmt=',')

我还可以通过在同一个单元格中放置两条线来将一个图堆叠在另一个图上

histoPlot(histo1,fmt=',')`
histoPlot(histo2,fmt=',')

但我收到警告

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  warnings.warn(message, mplDeprecation, stacklevel=1)

我已经能够发送警告(在Matplotlib: Adding an axes using the same arguments as a previous axes 之后),但代价是使我的函数无法堆叠。也就是说,函数的每次调用都会创建一个带有新绘图的新框架。我怎样才能摆脱这个警告并且仍然能够堆叠我的地块?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您每次在函数内使用ax = plt.axes() 定义一个新轴对象。如果要在同一图中绘制所有直方图,则必须传递该特定轴对象。以下是解释此问题的示例答案

    import matplotlib.pyplot as plt
    import numpy as np; np.random.seed(121)
    
    fig, ax = plt.subplots()
    
    def histoPlot(ax):
        ax.hist(np.random.normal(0, 1, 1000), bins=100)
    
    histoPlot(ax)
    histoPlot(ax)
    histoPlot(ax)
    plt.show()
    

    【讨论】:

    • 我实际上更喜欢这个答案而不是我的(我们交叉发布),但让我的答案更多pyplot-ish...
    【解决方案2】:

    通常的方法是返回轴

    def histoPlot(h,fmt='.',lighter_error=0.75, ax=None, **kwargs):
        #fig, ax = plt.subplots(1)
        if ax is None:
            ax = plt.axes()
        # ...
        return ax
    
    ax = histoPlot(histo1,fmt=',')
    histoPlot(histo2,fmt=',', ax=ax)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-27
      • 2018-01-20
      • 1970-01-01
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      相关资源
      最近更新 更多