I'd like to plot all the iterations in one plot for the matrix syn0, but the following code is showing just the last iteration and if I change the code it will open the plot 60000 times, how can I plot all the iteration in just one plot?
syn0 = 2 * np.random.random((3, 4)) - 1
arr_syn0[0][0].append(syn0[0][0])
arr_syn0[0][1].append(syn0[0][1])
arr_syn0[0][2].append(syn0[0][2])
arr_syn0[0][3].append(syn0[0][3])
arr_syn0[1][0].append(syn0[1][0])
arr_syn0[1][1].append(syn0[1][1])
arr_syn0[1][2].append(syn0[1][2])
arr_syn0[1][3].append(syn0[1][3])
arr_syn0[2][0].append(syn0[2][0])
arr_syn0[2][1].append(syn0[2][1])
arr_syn0[2][2].append(syn0[2][2])
arr_syn0[2][3].append(syn0[2][3])
plt.figure()
x=plt.imshow(syn0,aspect='auto', interpolation="nearest", cmap='YlOrRd_r', origin="upper")
plt.colorbar(x)
plt.title('syn1')
plt.show()
You say you want to plot all the iterations in one plot, but since you're iterating over 60000 images I guess what you want is to plot the new data on the same figure without opening a new one.
In order to do that you should use the imshow method on the first image only, and use the draw method on the other images, followed by the pause method that will call the GUI event loop and update the image.
Trying to reduce your code to a minimal, complete and verifiable example I'd do something like this:
import numpy as np
import matplotlib.pyplot as plt
firstImage = True
for j in range(5):
syn0 = 2 * np.random.random((3, 4)) - 1
if firstImage:
img=plt.imshow(syn0,aspect='auto', interpolation="nearest", cmap='YlOrRd_r', origin="upper")
firstImage = False
else:
img.set_data(syn0)
plt.pause(0.1)
plt.draw()
plt.title('syn1')
This code shows the different images on the same figure one after the other.
Hope this helps.
Related
I wanna display in a list of lists the images inside it using matplotlib. So for example I wanna have in the first row, the images of the first list, the second row, the images of the second list and so on. I tried this, but I obtain the images in each row, maybe because it will call over and over again subplot. How can I fix it?
index_plot=0
for query in list_plot:
for qm_images in query:
plt.subplot(3,5,index_plot+1)
plt.imshow(np.array(Image.open(qm_images)))
plt.show()
index_plot += 1
Instead of creating many subplots initially create a nested list of subplots with plt.subplots(), call imshow on each axis
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 6)
for i, query in enumerate(list_plot):
for j, qm_images in enumerate(query:
axs[i][j].imshow(np.array(Image.open(qm_images)))
plt.show()
I would like to create figures using matplotlib for example, based on matrix data. The matrix has 3 dimensions, x and y are size of a layer and n is the number of layers of my matrix.
I would like to display each layer separatly using an imshow for each layer. The matrix is loaded from a file, and before loading it I don't know the size of the matrix.
How can I automate figure generation ? It is always the same thing, but usually I'm doing it statically:
If I have 3 layer I'm doing it by hand :
import matplotlib.pyplot as plt
fig1 = plt.figure()
# my plots
fig2 = plt.figure()
# my plots
fig3 = plt.figure()
# my plots
But if I don't knowthe number of figure I cannot do it this way. I would like to create it using a loop:
for i in range(n):
figi = plt.figure()
But in doing this way I'm overwriting figi every time of course! How can I do to conserve all of my figures ?
Thanks for your help
I am trying to print about 42 plots in 7 rows, 6 columns, but the printed output in jupyter notebook, shows all the plots one under the other. I want them in (7,6) format for comparison. I am using matplotlib.subplot2grid() function.
Note: I do not get any error, and my code works, however the plots are one under the other, vs being in a grid/ matrix form.
Here is my code:
def draw_umap(n_neighbors=15, min_dist=0.1, n_components=2, metric='euclidean', title=''):
fit = umap.UMAP(
n_neighbors=n_neighbors,
min_dist=min_dist,
n_components=n_components,
metric=metric
)
u = fit.fit_transform(df);
plots = []
plt.figure(0)
fig = plt.figure()
fig.set_figheight(10)
fig.set_figwidth(10)
for i in range(7):
for j in range(6):
plt.subplot2grid((7,6), (i,j), rowspan=7, colspan=6)
plt.scatter(u[:,0], u[:,1], c= df.iloc[:,0])
plt.title(title, fontsize=8)
n=range(7)
d=range(6)
for n in n_neighbors:
for d in dist:
draw_umap(n_neighbors=n, min_dist=d, title="n_neighbors={}".format(n) + " min_dist={}".format(d))
I did refer to this post to get the plots in a grid and followed the code.
I also referred to this post, and modified my code for size of the fig.
Is there a better way to do this using Seaborn?
What am I missing here? Please help!
Both questions that you have linked contain solutions that seem more complicated than necessary. Note that subplot2grid is useful only if you want to create subplots of varying sizes which I understand is not your case. Also note that according to the docs Using GridSpec, as demonstrated in GridSpec demo is generally preferred, and I would also recommend this function only if you want to create subplots of varying sizes.
The simple way to create a grid of equal-sized subplots is to use plt.subplots which returns an array of Axes through which you can loop to plot your data as shown in this answer. That solution should work fine in your case seeing as you are plotting 42 plots in a grid of 7 by 6. But the problem is that in many cases you may find yourself not needing all the Axes of the grid, so you will end up with some empty frames in your figure.
Therefore, I suggest using a more general solution that works in any situation by first creating an empty figure and then adding each Axes with fig.add_subplot as shown in the following example:
import numpy as np # v 1.19.2
import matplotlib.pyplot as plt # v 3.3.4
# Create sample dataset
rng = np.random.default_rng(seed=1) # random number generator
nvars = 8
nobs = 50
xs = rng.uniform(size=(nvars, nobs))
ys = rng.normal(size=(nvars, nobs))
# Create figure with appropriate space between subplots
fig = plt.figure(figsize=(10, 8))
fig.subplots_adjust(hspace=0.4, wspace=0.3)
# Plot data by looping through arrays of variables and list of colors
colors = plt.get_cmap('tab10').colors
for idx, x, y, color in zip(range(len(xs)), xs, ys, colors):
ax = fig.add_subplot(3, 3, idx+1)
ax.scatter(x, y, color=color)
This could be done in seaborn as well, but I would need to see what your dataset looks like to provide a solution relevant to your case.
You can find a more elaborate example of this approach in the second solution in this answer.
Alright so i want to plot 421 in a 6x4 sub plot and i want this to create a new image after every 24th image. I've tried somethings before but it ends up giving normal 421 plots one below the other
for i in range(0,421):
a = df.iloc[i:i+1]
x = np.concatenate([a['t11_arms_number_a31_1_weighted_fraction'],a['t11_arms_number_a32_2_weighted_fraction'],a['t11_arms_number_a33_3_weighted_fraction'],a['t11_arms_number_a34_4_weighted_fraction'],a['t11_arms_number_a36_more_than_4_weighted_fraction'],a['t11_arms_number_a37_cant_tell_weighted_fraction']])
y = np.linspace(1,6,6)
plt.plot(y,x)
plt.show()
Whenever you call plt.show() it shows a plot. If you only want to show plots of groups of 24 subplots you simply call plt.show() once every 24 steps. I just plotted some lines in the example below.
import numpy as np
import matplotlib.pyplot as plt
for i in range(0,421):
x = np.linspace(0,1,100)
plt.plot(x,x+i)
if(i%24 == 0):
plt.show()
I am trying to follow the basic animation tutorial located here and adapting it to display an already computed dataset instead of evaluating a function every frame, but am getting stuck. My dataset involves XY coordinates over time, contained in the lists satxpos and satypos I am trying to create an animation such that it traces a line starting at the beginning of the dataset through the end, displaying say 1 new point every 0.1 seconds. Any help with where I'm going wrong?
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
Code here creates satxpos and satypos as lists
fig = plt.figure()
ax = plt.axes(xlim=(-1e7,1e7), ylim = (-1e7,1e7))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
line.set_data(satxpos[i], satypos[i])
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames = len(satxpos), interval = 1, blit=True)
Edit: The code runs without errors, but generates a blank plot window with no points/lines displayed and nothing animates. The dataset is generated correctly and views fine in a static plot.
In order to "trace a line starting at the beginning of the dataset through the end" you would index your arrays to contain one more element per timestep:
line.set_data(satxpos[:i], satypos[:i])
(Note the :!)
Everything else in the code looks fine, such that with the above manipulation you should get and extending line plot. You might then want to set interval to something greater than 1, as that would mean 1 millesecond timesteps (which might be a bit too fast). I guess using interval = 40 might be a good start.
Your code looks correct! So long as satxpos and satypos are both configured and initialized properly, I believe everything else is valid!
One part of the code you do not show in your question is the invocation of the anim.save() and plt.show() functions, which are both necessary for your code to work (as per the tutorial you shared!)
You would therefore need to add something like:
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
to the end of your code to create the animation (and show it, I presume)!
Hope it helps!
Source - Matplotlib Animation Tutorial
I saw you mentioned "the parts that generate satxpos and satypos do create valid datasets. I can view those as a static plot just fine". But my guess is still the problem originated from your satxpos and satypos.
One way you can trouble shoot is to replace your two functions and animation code with line.set_data(satxpos[i], satypos[i]). Set i as 0, 1, ... and see if you can see the plot. If not, your satxpos and satypos are not as valid as you claimed.
As an example, a valid satxpos and satypos can be like this:
x = np.array([np.linspace(-1e7, 1e7, 1000)])
i = 200
satxpos = x.repeat(i, axis=0)
satypos = np.sin(2 * np.pi * (satxpos - 0.01 * np.arange(i).reshape(-1, 1).repeat(satxpos.shape[1], axis=1)))
satypos *= 1e7 / 2
This works with the code you provided thus indicating the code you've shown us is fine.
Edit in response to comments:
If your satxpos and satypos are just np.linespace, the animation loop will get just one point with (satxpos[i], satypos[i]) and you won't see the point on the plot without a setting like marker='o'. Therefore, you see nothing in your animation.