简体   繁体   中英

How to avoid images overlapping when plotting with pandas.Series.plot()?

I have a piece of code like this.

import pandas as pd

line1 = [1.23, 4.55, 6.72, 6.71]
line2 = [9.23, 7.52, 7.12, 9.71, 5.21]

data = [line1, line2]
for d in data:
    data_series = pd.Series(d)
    result = data_series.plot(xlabel='Index', ylabel='Current', title=f'{d[0]}', grid=True, subplots=False)
    fig = result.get_figure()
    fig.savefig(f'{d[0]}.png')

I want to use the above code to generate 2 image files, each with a single line in it.

The problem I have is that the second image contains the first image.

First Image:

第一张图片

Second Image:

在此处输入图像描述

How can I modify my code so that the second image only contains the line that represents line2 ?

I'm not sure if pandas alone will help you but as it is using matplotlib as the backend for plotting you could do as follows:

This creates a new figure for each column (series) that you'd like to plot and only plots one line per figure.

import matplotlib.pyplot as plt
import pandas as pd

line1 = [1.23, 4.55, 6.72, 6.71]
line2 = [9.23, 7.52, 7.12, 9.71, 5.21]

data = [line1, line2]
for d in data:
    fig, ax = plt.subplots()
    data_series = pd.Series(d)
    data_series.plot(xlabel='Index', ylabel='Current', title=f'{d[0]}', grid=True, subplots=False)
    fig.savefig(f'{d[0]}.png')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM