Home > Enterprise >  plotting dataframe values in loop
plotting dataframe values in loop

Time:01-28

I have a csv file named as data.csv and it contain [10000 rows x 1 columns] and i read the data as

a=read_csv("data.csv")

print(a)

                                                  dt
0     3.5257,3.5257,3.5257,3.5257,3.5257,3.5257,3.52...
1     3.3414,3.3414,3.3414,3.3414,3.3414,3.3414,3.34...
2     3.5722,3.5722,3.5722,3.5722,3.5722,3.5722,3.57...
.....

Now I want to plot each indexed rows in loop and want to save each plot in the name of index values . For example

i need to produce 0.jpg by using o indexed values ---->  3.5257,3.5257,3.5257,3.5257,3.5257,3.5257,3.52...
similarly 1.jpg by using 1 index values---->  3.3414,3.3414,3.3414,3.3414,3.3414,3.3414,3.34...

My code

a=read_csv("data.csv")
print(a)
for data in a:
    plt.plot(data)
    

Hope experts will help me providing the answer.Thanks.

CodePudding user response:

Use savefig to create image file:

import matplotlib.pyplot as plt

for name, data in a['dt'].str.split(',').items():
    plt.plot(data)
    plt.savefig(f'{name}.jpg')
    plt.close()

0.jpg enter image description here

1.jpg enter image description here

CodePudding user response:

With the following file.csv example:

3.5257,3.5257,3.5257,3.5257,3.5257,3.5257,3.52
3.3414,3.3414,3.3414,3.3414,3.3414,3.3414,3.34
3.5722,3.5722,3.5722,3.5722,3.5722,3.5722,3.57

Here is one way to do it with Pandas iterrows and Python f-strings:

import matplotlib.pyplot as plt
import pandas as pd


df = pd.read_csv("../file.csv", header=None)

for i, row in df.iterrows():
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 4))
    ax.plot(row)
    fig.savefig(f"./{i}.png")
  • Related