简体   繁体   English

使用 pandas.Series.plot() 绘图时如何避免图像重叠?

[英]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.我想使用上面的代码生成 2 个图像文件,每个文件都有一行。

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 ?如何修改我的代码,使第二个图像只包含代表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:我不确定 pandas 是否会单独帮助您,但由于它使用 matplotlib 作为绘图的后端,您可以执行以下操作:

This creates a new figure for each column (series) that you'd like to plot and only plots one line per figure.这将为您想要 plot 的每一列(系列)创建一个新图形,并且每个图形只绘制一条线。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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