Предупреждение «Добавление осей с использованием одинаковых аргументов» и пользовательская функция построения - PullRequest
0 голосов
/ 15 марта 2019

Я сделал функцию, которая заставляет гистограммы отображать то, что мне нравится (с ошибками!).

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: добавление осей с использованием тех же аргументов, что и у предыдущих осей ), но только ценой того, что моя функция не может быть наращиваемой. То есть каждый вызов функции создает новый кадр с новым графиком. Как я могу избавиться от этого предупреждения и все еще иметь возможность составлять свои графики?

Ответы [ 2 ]

2 голосов
/ 15 марта 2019

Обычным способом будет возврат осей

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)
1 голос
/ 15 марта 2019

Вы определяете новый объект оси каждый раз внутри своей функции, используя 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()

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...