Plotting multiple figures in a loop - python

I am trying to plot a diagram inside a loop and I expect to get two separate figures, but Python only shows one figure instead. In fact, it seems Python plots the second figure over the first one. This is the code I am using:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10)
y = np.arange(0,10)
for _ in range(2):
plt.plot(x,y)
plt.show()
It worth noting that I am working with Python 2.7 in PyCharm environment. Any kind of advice is appreciated.

Try the following:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10)
y = np.arange(0,10)
for _ in range(2):
plt.figure() # add this statement before your plot
plt.plot(x,y)
plt.show()

This could do:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10)
y = np.arange(0,10)
f, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(x, y)
ax2.plot(x, y)
plt.show()

Related

Filling subplot with colormap - Matplotlib LogNorm does work in python 3 anymore

I had pretty nice plots looking like this created a while ago in python 2.7.
Now it appears that LogNorm does not work anymore.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
fig = plt.figure()
ax = fig.add_subplot(111)
# creating logspaced values for colorbar
x = np.logspace(-8,-3,6)
yarr = np.vstack((x,))
print(yarr)
# check if yarr is really logspaced
ax.plot(yarr, [1e1]*len(yarr), 'w.-')
# fill box with colorbar - this does not work anymore
ax.imshow(yarr, extent=(1e-8, 1e-3, 1, 1e4), norm=LogNorm(vmin=1e-8, vmax=1e-3))
ax.set_xscale("log")
ax.set_yscale("log")
Output now
Thanks in advance.
It was pointed out to me that it is a problem of matplotlib:
https://github.com/matplotlib/matplotlib/issues/7661/
import numpy as np
import matplotlib.pyplot as plt
tmp = np.arange(199).reshape(1, 199)
y = np.logspace(0, -4, 2)
x = np.logspace(-8, -3, 200)
fig, ax = plt.subplots()
ax.set_xscale('log')
ax.set_yscale('log')
ax.pcolormesh(x, y, tmp)
plt.show()
This solves the problem.

Matplotlib not plotting all points

I am trying to plot a 3D-Array in matplotlib, but I only see a linear output. The expected output was a 10x10x10 cube.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
points = np.zeros((10, 10, 10))
for x in range(10):
for y in range(10):
for z in range(10):
points[x][y][z] = z
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(points[:,0],points[:,1],points[:,2])
plt.show()
OK, you were very, very close. I didn't realize how close until I tried it. The problem you had was that you made points a 3D array where each entry had a value. It needed to be a 2D array, 1000 x 3.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
points = []
for x in range(10):
for y in range(10):
for z in range(10):
points.append((x,y,z))
points = np.array(points)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(points[:,0],points[:,1],points[:,2])
plt.show()
You've got a good answer by Tim. However, there are alternatives approaches. For example, there is np.meshgrid() that are often used in your situation to produce and manipulate data. Here is the code to generate array of data and produce sample plot.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n1 = 10 #number of grid rows/columns
xg, yg = np.meshgrid(np.arange(n1),np.arange(n1))
for i in np.arange(n1):
zg = np.ones(xg.shape) * i
ax.scatter(xg, yg, zg, s=3, c='k')
lim = n1 + 0.1*n1
ax.set_xlim3d(-0.1*n1, lim)
ax.set_ylim3d(-0.1*n1, lim)
ax.set_zlim3d(-0.1*n1, lim)
# set viewing angle
ax.azim = 120 # z rotation (default=270); 160+112
ax.elev = 35 # x rotation (default=0)
ax.dist = 10 # zoom (define perspective)
plt.show()

matplotlab How can I plot points in a loop using one array

This is a simplified example of a problem I am having.
import matplotlib.pyplot as plt
for i in range(0,10):
plt.plot(i, i + 1)
plt.show()
shows this. and
x = y = []
for i in range(0,10):
x.append(i)
y.append(i + 1)
plt.plot(x, y,)
plt.show()
shows this.
How can I plot points in a loop so that I don't need to create two arrays?
Try this-
import matplotlib.pyplot as plt
for i in range(0,10):
plt.plot(i, i + 1, color='green', linestyle='solid', linewidth = 3,
marker='o')
plt.show()
Pass array as the first argumet to plt.plot(), this would plot y using x as index array 0..N-1:
import matplotlib.pyplot as plt
# plot y using x as index array 0..N-1
plt.plot(range(10))
plt.show()
You'll find more interesting information at plt.plot().
You can do it with:
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
fig, ax = plt.subplots()
max =10
for i in range(0,max):
#scatter:
#s=0 to make dissapeared the scatters
ax.scatter(i, i + 1,s=1,facecolor='blue')
#lines
if i > 0:
lc = LineCollection([[(i-1, i),(i, i+1)]])
ax.add_collection(lc)
plt.show()
result:

Plot very small values with matplotlib in jupyter

I am trying to plot some extremely small values with matplotlib in jupyter notebook (on a macbook pro). However, regardless if I set the y-axis limits, all I get is a flat line. What I am after is something like the example (png) below with regard to y-axis notation. I also tried the same example outside of jupyter and I still get the same results. Here's the code suggested by Andrew Walker on my previous question:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(13,6))
ax = fig.add_subplot(111)
plt.hold(True)
xs = np.linspace(0, 1, 101)
ys = 1e-300 * np.exp(-(xs-0.5)**2/0.01)
ax.plot(xs, ys, marker='.')
Here's what I get:
And here's what I'm after:
The easiest thing to do is to just plot your values multiplied by 10^300, and then change the y-axis label:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(13,6))
ax = fig.add_subplot(111)
plt.hold(True)
xs = np.linspace(0, 1, 101)
ys = np.exp(-(xs-0.5)**2/0.01)
ax.plot(xs, ys, marker='.')
ax.set_ylabel(r'Value [x 10^{-300}]')
You can use the set_ylim method on your axes object to do what you need, simply change your code to this and it would do what you need:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(13,6))
ax = fig.add_subplot(111)
plt.hold(True)
xs = np.linspace(0, 1, 101)
ys = 1e-300 * np.exp(-(xs-0.5)**2/0.01)
ax.set_ylim([0,10^-299])
ax.plot(xs, ys, marker='.')
you may like to check This link for more info on this subject.

How to make a 3D plot in matplotlib from data z=f(x,y) read from file

I need to create a 3D plot in matplotlib. I am reading Z values from a text file formated as 1D array. This data represents value for every point on a 50x50 square. So first 50 values are for points (0,0),(1,0)..(49,0), next 50 are for (0,1),(1,1) and so on. So far i have written the following code:
import matplotlib.pyplot as plt
import numpy as np
fp=open(path,"r")
a=fp.read()
buffer=""
data=[]
for i in a:
if i != ' ':
buffer=buffer+i
else:
data.append(float(buffer))
buffer=""
fp.close()
values=data[50*50:50*50*2]
x=np.linspace(0,50,50)
y=np.linspace(0,50,50)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, values)
plt.show()
But of course it is not working. I searched the Internet for some clues but without any success. Can someone show me how I should done it? I would be more than grateful.
First, you forgot to import Axes3D: import matplotlib.pyplot as plt.
Second, you code has strange meaningless line: values[50*50*nb:50*50*(nb+1)] and indentation is wrong in your code.
Third, to plot regularly gridded data you do not need plot_trisurf, use plot_surface:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x=np.linspace(0,50,50)
y=np.linspace(0,50,50)
X, Y = np.meshgrid(x, y)
values = np.sqrt(X**2 + Y**2)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(x, y, values)
plt.show()
Look for examples: http://matplotlib.org/examples/mplot3d/surface3d_demo.html

Categories