matplotlib中图形的意外叠加

时间:2016-02-25 14:13:49

标签: python matplotlib

enter image description here enter image description here

看起来第一张图中的数据点意外地覆盖了第二张图。我正在运行的代码正在运行几次,当我第一次运行时很短,第二次运行它时,我有一个较长的时间段,而短期内的数据点也是较长时间段的一部分。

那么在开始构建图形之前有没有办法清理图表?

您可以在此处查看构建图表的代码:

def create_graph(self, device):

    # 800 and 355 pixels.
    ticks = 5
    width = 8
    height = 3.55

    dpi = 100
    bgcolor = '#f3f6f6'

    font = {
        'size': 16,
        'family': 'Arial'
    }
    plt.rc('font', **font)

    # size of figure and setting background color
    fig = plt.gcf()
    fig.set_size_inches(width, height)
    fig.set_facecolor(bgcolor)

    # axis color, no ticks and bottom line in grey color.
    ax = plt.axes(axisbg=bgcolor, frameon=True)
    ax.xaxis.set_ticks_position('none')
    ax.spines['bottom'].set_color('#aabcc2')
    ax.yaxis.set_ticks_position('none')

    # removing all but bottom spines
    for key, sp in ax.spines.items():
        if key != 'bottom':
            sp.set_visible(False)

    # setting amounts of ticks on y axis
    yloc = plt.MaxNLocator(ticks)
    ax.yaxis.set_major_locator(yloc)


    x_no_ticks = 8
    # Deciding how many ticks we want on the graph
    locator = AutoDateLocator(maxticks=x_no_ticks)
    formatter = AutoDateFormatter(locator)
    # Formatter always chooses the most granular since we have granular dates
    # either change format or round dates depending on how granular
    # we want them to be for different date ranges.
    formatter.scaled[1/(24.*60.)] = '%d/%m %H:%M'

    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)

    # turns off small ticks
    plt.tick_params(axis='x',
                    which='both',
                    bottom='on',
                    top='off',
                    pad=10)
    # Can't seem to set label color differently, changing tick_params color changes labels.
    ax.xaxis.label.set_color('#FFFFFF')

    # setting dates in x-axis automatically triggers use of AutoDateLocator
    x = [datetime.fromtimestamp(point['x']) for point in device['data']]
    y = [point['y'] for point in device['data']]
    plt.plot(x, y, color='#53b4d4', linewidth=2)

    # pick values for y-axis
    y_ticks_values = np.array([point['y'] for point in device['data']])
    y_ticks = np.linspace(y_ticks_values.min(), y_ticks_values.max(), ticks)
    y_ticks = np.round(y_ticks, decimals=2)
    plt.yticks(y_ticks, [str(val) + self.extract_unit(device) for val in y_ticks])
    # plt.ylim(ymin=0.1)  # Only show values of a certain threshold.

    plt.tight_layout()
    buf = io.BytesIO()
    plt.savefig(buf,
                format='png',
                facecolor=fig.get_facecolor(),
                dpi=dpi)

1 个答案:

答案 0 :(得分:1)

您必须在plt.close()之后添加plt.savefig()。因此,下一个plt.gcf()电话不会捕捉该数字。