Issue
I have two lists and I want to take item names from the list and use it to a loop. I want to take the name of dataframe from the df_compressed_list and plot a figure with two columns of that dataframe and then save that figure to a folder. It should take the name of the figure from the plot_image_list Please see the codes below.
df_compressed_list= ['df_compressed_1','df_compressed_2','df_compressed_3','df_compressed_4','df_compressed_5','df_compressed_6','df_compressed_7','df_compressed_8','df_compressed_9','df_compressed_10','df_compressed_11','df_compressed_12','df_compressed_13','df_compressed_14']
plot_image_list= ['compressed_1','compressed_2','compressed_3','compressed_4','compressed_5','compressed_6','compressed_7','compressed_8','compressed_9','compressed_10','compressed_11','compressed_12','compressed_13','compressed_14']
for i in df_compressed_list:
plt.figure(100,figsize=(10,5))
plt.plot(i['time'], i['voltage'])
for j in plot_image_list:
plt.savefig('images\j.PNG')
plt.close()
['time'] and ['voltage'] are columns names of a pandas dataframe.I already created dataframe with respective names. I tried the above code but it doesn't work. It shows
TypeError: list indices must be integers or slices, not str
What I want it to do is, it will take the name one by one from the list and put the name in plt.plot(i['time'], i['voltage'])
So that it would look like this
plt.plot(df_compressed_1['time'], df_compressed_1['voltage'])
And
plt.savefig('images\j.PNG')
so that it would look like this
plt.savefig('images\compressed_1.PNG')
In every iteration it should take the next name of df_compressed_list list and plot_image_list. Can someone tell me how to achieve this?
Solution
I'am still not exactly sure want you trying to accomplish, but i think this may help you. Maybe you can just take the concept of this and rewrite it to fit your problem.
I created two pandas DataFrames df1
and df2
these could also be opened from a csv etc. with df1 = pd.read_csv()
Then I put them into a list df_list
.
Now i made a loop that loops over all of the DataFrames and saves the plot of the voltage
over the time
in a figs
folder.
import pandas as pd
import matplotlib.pyplot as plt
df1 = pd.DataFrame(
{
"time": [0, 1, 2, 3, 4, 5],
"voltage" : [0, 23, 44, 19, 7, 3],
}
)
df2 = pd.DataFrame(
{
"time": [0, 1, 2, 3, 4, 5],
"voltage" : [0, 200, 404, 200, 190, 150],
}
)
df_list = [df1, df2]
for df_number in range(len(df_list)):
fig = plt.figure(100, figsize=(10, 5))
ax = fig.add_axes([0,0,1,1])
# df_list[index] -> df1 .. df2; df2["voltage"] -> [0, 200, 404, 200, 190, 150]
ax.plot(df_list[df_number]["time"], df_list[df_number]["voltage"])
fig.savefig("figs/figure{}.jpg".format(df_number))
The figs folder must be created manually. Look at pathlib for more info on working with filenames and paths.
Answered By - perperam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.