For loop in matplotlib only plots first iteration - python

I want to read several columns from a csv file and plot them on a single window. What I currently have is this:
fig1=pl.figure(num=1, figsize=(8, 4), dpi=80, facecolor='w',edgecolor='k')
a=np.random.rand(50,9)
ax = pl.gca()
for i in range(0,6,2):
ax.errorbar(a[:,i], a[:,i+1], yerr= a[:,i+2])
ax.set_xscale('log')
ax.set_xlim(1e19, 1e22)
pl.show()
I get no error message, but the output is a plot with only the first iteration, when there should be three in this sample file. I have put different parts of the code in the loop but at best I get the first plot window and two empty windows which is not what I am looking for either. Why isn't the for loop cycling through the i values? Or assuming is it cycling through why is it only plotting the first one? Thanks!
UPDATE: thanks tcaswell, the x range was simply too restrictive. Classical case of not looking at the data close enough. Embarrassing.

Related

Generating subplot with data generated within a for loop (i.e. creating a subplot and adding new plots as the loop iterates)

I am a first poster here, please bear with me as I try to present my issue :)
I have a for loop in which I am generating a set of data (in this case a list, but could be converted to a data frame if needed) and each time the for loop iterates, I generate a histogram with new data for that specific loop that I want to add to my subplot. See below what I have tried:
I have tried the following:
well_ID = ["A2","A3","A4","B2","B3","B4"]
FOV = range(1,31)
for index_row,i in enumerate(well_ID):
for j in FOV:
#Here I have plenty of functions analysing images and thresholding them and eventually I get to the following:
my_data_list = [#huge dataset with lots of values]
#What I would like to do:
fig, axes = plt.subplots(nrows=6, ncols=5)
fig.subplots_adjust(hspace=0.5)
axes[index_row,j].hist(my_data_list, bins = 50, rwidth=0.9,color = 'skyblue')
When I run the above code I get a subplot that only plots each loop dataset into the specified position in axes[index_row,j] without adding previous loops data (as in updating the previous subplot with the new loop data).
Can anybody help with this? Thank you very much!!! :D
(feel free to ask any specific questions to make it clearer, I just tried to simplify it because the actual code is very long)

How to loop over all subplot in a figure to add a new series in it?

Doing the following allow me to create a figure with subplots :
DF.plot(subplots=True, layout=(9,3),figsize = (20,40),sharex=False)
plt.tight_layout()
plt.show()
This works very well. However, I would like to add to all these subplots a new series that would be the same for each subplot.
I think it is possible by browsing all subplot in the figure and then edit each one.
I don't know how to do it and don't know the smartest way to do it, maybe avoid using loop would be faster but I don't know if it is doable.
Assuming that the common serie is DF2['Datas'], how do I add it to all subplots?
DataFrame.plot returns a matplotlib.axes.Axes or numpy.ndarray of them.
axs = DF.plot(subplots=True, layout=(9,3),figsize = (20,40),sharex=False)
for ax in axs.ravel():
DF2['Datas'].plot(ax=ax)

How to display many plots together in the same output -python

[shot from Jupyter][1]
I am trying to display two plots output from function to be together in the same output.
Can anyone help?
thanks
[1]: https://i.stack.imgur.com/ABXMj.png
You can either use plt.subplots() or else you can do the one as shown in the picture too by coding all the plots together and then giving plt.show() at last.
Below each plot code use plt.plot():
fig, axes = plt.subplots(1,2)
plt.plot(ax=axes[0])
plt.plot(ax=axes[1])

Matplotlib.pyplot - how to save a histogram in a variable for later access?

Due to data access patterns, I need to save various histograms in a Python list and then access them later to output as part of a multi-page PDF.
If I save the histograms to my PDF as soon as I create them, my code works fine:
def output_histogram_pdf(self, pdf):
histogram = plt.hist(
x=[values], bins=50)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
if isinstance(pdf, PdfPages):
pdf.savefig()
But if I instead save them to a list so I can later manipulate the order, I run into trouble.
histogram_list.append(histogram)
Then later
for histogram in histogram_list:
plt.figure(histogram)
pdf.savefig()
This does not work. I'm either saving the wrong thing, or I don't know how to properly open what I've saved.
I've spent quite some time fruitlessly googling for a working solution, but so many of the terms involved are sufficiently vague that I get tons of different types of issues in my search results. Any help would be greatly appreciated, thanks!
Short Answer
You can use plt.gcf()
When creating your graph, after setting xlabel, ylabel, and title, append the figure to histogram list.
histogram_list.append(plt.gcf())
You can then iterate over the list later and call savefig.
Long Answer
plt.hist doesn't return the figure object. However, the figure object can be obtained using gcf (Get Current Figure).
In case you do not want to use the current figure, you could always create the figure yourself, using plt.figure or plt.subplot.
Either way, since you are already plotting the histogram and setting the labels for the figure, you'd want to append the figure to the list.
Option 1: using gcf
histogram = plt.hist(
x=[values], bins=50)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
histogram_list.append(plt.gcf())
Option 2: create your own figure
figure = plt.figure(figsize=(a,b,))
# draw histogram on figure
histogram_list.append(figure)
Each histogram is formed by (n,bins,patches) where n are the values for each bin, bins are the bins edges (1 more than n), and patches are the artists to create the bars.
Most simply, try to plot each histogram as
for histogram in histogram_list:
n = histogram[0]
bins = histogram[1]
plt.plot(bins[:-1], n, '-', ds='steps-pre')

In Python for loop, how to create legends for plots?

I have successfully created a figure of four sub-plots and two of subplots having double y-axis features as shown below. Each subplot has many different plots. I wanted to add a legend. But, I could not do it with code. The figure is given below:
My code is given below:
fig, axs = plt.subplots(2,2,figsize=(17,10))
fig.legend(loc="center right", fontsize=13,fancybox=True, framealpha=1, shadow=True, borderpad=1)
plt.rc('font',family='Times New Roman')
.
.
for i,j in zip(IV_start_index,IV_start_index[1:]): # This is simple code to access present and next element in a list
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_theo,'bs',label="Theoretical")
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_act,'rd',label="Actual")
.
.
plt.suptitle('A NIST Module %s power loss analysis'%(module_allData_df['Time'].loc[i].strftime('%Y-%m-%d')),fontsize=18) #
plt.savefig('All_day_power_loss')
The output is:
No handles with labels found to put in legend.
Could you help me to correct my code?
Corrections:
I did change the code as given below.
for i,j in zip(IV_start_index,IV_start_index[1:]): # This is simple code to access present and next element in a list
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_theo,'bs',label="Theoretical")
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_act,'rd',label="Actual")
axs[0][0].legend()
It has created many legends.The output figure is given below:
If you don't provide the legend entries within the legend() function, it should be placed after the label-entries in the plot commands. Otherwise legend cannot know what to list.
If you want to have a legend within each subplot, you should call axs[i][j].legend() within a loop (or call axs[0][0].legend(), axs[0][1].legend(), ... manually for each subplot of course). The point is: fig.legend() is a legend on figure level, i.e. one legend for all subplots together. This should be called once outside of the loop.
After a series of trails, I did the following to my code:
for i,j in zip(IV_start_index,IV_start_index[1:]): # This is simple code to access present and next element in a list
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_theo,'bs')
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_act,'rd')
axs[0][0].legend(['Theoretical','Actual'])
.
.
My output is:

Categories

Resources