The diagram should only show the masked values. As in the (manipulated) figure on the right side.
Default shows all values. In 2d diagramms there is no problem.
Is it also possible in 3d diagrams? If yes, how to?
import matplotlib.pyplot as plt
import numpy as np
Z = np.array([
[ 1, 1, 1, 1, 1, ],
[ 1, 1, 1, 1, 1, ],
[ 1, 1, 1, 1, 1, ],
[ 1, 1, 1, 1, 1, ],
[ 1, 1, 1, 1, 1, ],
])
x, y = Z.shape
xs = np.arange(x)
ys = np.arange(y)
X, Y = np.meshgrid(xs, ys)
M = np.ma.fromfunction(lambda i, j: i > j, (x, y))
R = np.ma.masked_where(M, Z)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, R)
#ax.plot_wireframe(X, Y, R)
#ax.plot_trisurf(X.flatten(), Y.flatten(), R.flatten())
fig.show()
Update: Matplotlib >= 3.5.0
As pointed out by eric's comment, the issue is solved in matplotlib <= 3.5.0, and the code from the OP works as expected. So right now, if you can probably your best option is to update matplotlib.
The original answer is left here for situations were updating matplotlib might not be an option.
Old: Matplotlib < 3.5.0
The bad news is that it seems that plot_surface() just ignores masks. In fact there is an open issue about it.
However, here they point out a workaround that although it's far from perfect it may allow you get some acceptable results. The key issue is that NaN values will not be plotted, so you need to 'mask' the values that you don't want to plot as np.nan.
Your example code would become something like this:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
Z = np.array([
[ 1, 1, 1, 1, 1, ],
[ 1, 1, 1, 1, 1, ],
[ 1, 1, 1, 1, 1, ],
[ 1, 1, 1, 1, 1, ],
[ 1, 1, 1, 1, 1, ],
])
x, y = Z.shape
xs = np.arange(x)
ys = np.arange(y)
X, Y = np.meshgrid(xs, ys)
R = np.where(X>=Y, Z, np.nan)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, R, rstride=1, linewidth=0)
fig.show()
*I had to add the rstride=1 argument to the plot_surface call; otherwise I get a segmentation fault... o_O
And here's the result:
Related
I am trying to create a python program in which the user inputs a set of data and the program spits out an output in which it creates a graph with a line/polynomial which best fits the data.
This is the code:
from matplotlib import pyplot as plt
import numpy as np
x = []
y = []
x_num = 0
while True:
sequence = int(input("Input 1 number in the sequence, type 9040321 to stop"))
if sequence == 9040321:
poly = np.polyfit(x, y, deg=2, rcond=None, full=False, w=None, cov=False)
plt.plot(poly)
plt.scatter(x, y, c="blue", label="data")
plt.legend()
plt.show()
break
else:
y.append(sequence)
x.append(x_num)
x_num += 1
I used the polynomial where I inputed 1, 2, 4, 8 each in separate inputs. MatPlotLib graphed it properly, however, for the degree of 2, the output was the following image:
This is clearly not correct, however I am unsure what the problem is. I think it has something to do with the degree, however when I change the degree to 3, it still does not fit. I am looking for a graph like y=sqrt(x) to go over each of the points and when that is not possible, create the line that fits the best.
Edit: I added a print(poly) feature and for the selected input above, it gives [0.75 0.05 1.05]. I do not know what to make of this.
Approximation by a second degree polynomial
np.polyfit gives the coefficients of a polynomial close to the given points. To plot the polynomial as a smooth curve with matplotlib, you need to calculate a lot of x,y pairs. Using np.linspace(start, stop, numsteps) for the xs, numpy's vectorization allows calculating all the corresponding ys in one go. E.g. ys = a * x**2 + b * x + c.
from matplotlib import pyplot as plt
import numpy as np
x = [0, 1, 2, 3, 4, 5, 6]
y = [1, 2, 4, 8, 16, 32, 64]
plt.scatter(x, y, color='crimson', label='given points')
poly = np.polyfit(x, y, deg=2, rcond=None, full=False, w=None, cov=False)
xs = np.linspace(min(x), max(x), 100)
ys = poly[0] * xs ** 2 + poly[1] * xs + poly[2]
plt.plot(xs, ys, color='dodgerblue', label=f'$({poly[0]:.2f})x^2+({poly[1]:.2f})x + ({poly[2]:.2f})$')
plt.legend()
plt.show()
Higher degree approximating polynomials
Given N points, an N-1 degree polynomial can pass exactly through each of them. Here is an example with 7 points and polynomials of up to degree 6,
from matplotlib import pyplot as plt
import numpy as np
x = [0, 1, 2, 3, 4, 5, 6]
y = [1, 2, 4, 8, 16, 32, 64]
plt.scatter(x, y, color='black', zorder=3, label='given points')
for degree in range(0, len(x)):
poly = np.polyfit(x, y, deg=degree, rcond=None, full=False, w=None, cov=False)
xs = np.linspace(min(x) - 0.5, max(x) + 0.5, 100)
ys = sum(poly_i * xs**i for i, poly_i in enumerate(poly[::-1]))
plt.plot(xs, ys, label=f'degree {degree}')
plt.legend()
plt.show()
Another example
x = [0, 1, 2, 3, 4]
y = [1, 1, 6, 5, 5]
import numpy as np
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 2, 4, 8]
coeffs = np.polyfit(x, y, 2)
print(coeffs)
poly = np.poly1d(coeffs)
print(poly)
x_cont = np.linspace(0, 4, 81)
y_cont = poly(x_cont)
plt.scatter(x, y)
plt.plot(x_cont, y_cont)
plt.grid(1)
plt.show()
Executing the code, you have the graph above and this is printed in the terminal:
[ 0.75 -1.45 1.75]
2
0.75 x - 1.45 x + 1.75
It seems to me that you had false expectations about the output of polyfit.
I would like to obtain a smooth curve going through specific points with integer coordinates. Instead of that I get straight line segments between the points. I tried interp1d(x,y,kind='cubic') and also CubicSpline, nothing works. Here is my code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d,CubicSpline
x = np.arange(34)
y = [8,3,0,1,6,2,1,7,6,2,0,2,6,0,1,6,2,2,0,2,7,0,2,8,6,3,6,2,0,1,6,2,7,2]
f = CubicSpline(x, y)
plt.figure(figsize=(10,3))
plt.plot(x, y, 'o', x, f(x))
plt.show()
and here is the result:
Can you tell me how to get smooth curves instead?
Now you are using the original x-values to draw the curve. You need a new array with much more intermediate x-values. Numpy's np.linspace() creates such an array between a given minimum and maximum.
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d, CubicSpline
y = [8, 3, 0, 1, 6, 2, 1, 7, 6, 2, 0, 2, 6, 0, 1, 6, 2, 2, 0, 2, 7, 0, 2, 8, 6, 3, 6, 2, 0, 1, 6, 2, 7, 2]
x = np.arange(len(y))
f = CubicSpline(x, y)
plt.figure(figsize=(10, 3))
xs = np.linspace(x.min(), x.max(), 500)
plt.plot(x, y, 'o', xs, f(xs))
plt.tight_layout()
plt.show()
I am adding patches according to a list of ones and zeros (e.g. [1, 0, 1, 1, 0, 0, 1, 0, 1, 0]). I want to add patches where there are ones using matplotlib and leave the zeros empty. However, trying the following code raises a list index out of range error:
fig = plt.figure()
ax = plt.axes()
self.patches = []
for i, val in enumerate(my_list):
if val == 1:
self.patches.append(plt.Rectangle((i, 0), 0.9, 1, angle=0.0,
facecolor='r', edgecolor='w',
linewidth='2.0',
animated=False))
ax.add_patch(self.patches[i])
The only thing I can think of is using an else statement in the code above to add a rectangle with the same colour as the background for the zeros. Is there an empty patch object that one could use instead? I want the patches to be in the same position as the ones in the list.
use color='none' to set all colors (facecolor and edgecolor to invisible).
alternatively, you can pass visible=False to the constructor to hide the patch.
Your loop could be:
my_list = [1, 0, 1, 1, 0, 0, 1, 0, 1, 0]
patches = []
fig, ax = plt.subplots()
for i, val in enumerate(my_list):
p = plt.Rectangle((i, 0), 0.9, 1, angle=0.0,
facecolor='r', edgecolor='w',
linewidth='2.0',
animated=False, visible=bool(val))
patches.append(p)
ax.add_patch(p)
Sure, you can pass an empty patch to Matplotlib, but I wouldn't unless for some reason you want matplotlib to know about your missing data:
fig = plt.figure()
ax = plt.axes()
self.patches = []
for i, val in enumerate(my_list):
if val == 1:
self.patches.append(plt.Rectangle((i, 0), 0.9, 1, angle=0.0,
facecolor='r', edgecolor='w',
linewidth='2.0',
animated=False))
ax.add_patch(self.patches[i])
else:
self.patches.append(None)
Using matplotlib, I am trying to create a 3d plot that has three semi-transparent planes along the xy, yz, and xz planes. I am basing my code off of this post, which has a partial workaround for a transparency bug reported three years ago.
If you try out the below code and rotate the graph, you'll see that there are sudden color shifts in the areas where the planes overlap. For example below you see the center area suddenly change from green to blue. Is there a further workaround to prevent this?
Here is my code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d as mp3d
xy = [ (-1, -1, 0),
( 1, -1, 0),
( 1, 1, 0),
(-1, 1, 0),
]
yz = [ (0, -1, -1),
(0, 1, -1),
(0, 1, 1),
(0, -1, 1),
]
xz = [ (-1, 0, -1),
( 1, 0, -1),
( 1, 0, 1),
(-1, 0, 1),
]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter([-1, -1, -1, -1, 1, 1, 1, 1], [-1, -1, 1, 1, -1, -1, 1, 1], [-1, 1, -1, 1, -1, 1, -1, 1])
face1 = mp3d.art3d.Poly3DCollection([xy], alpha=0.5, linewidth=1)
face2 = mp3d.art3d.Poly3DCollection([yz], alpha=0.5, linewidth=1)
face3 = mp3d.art3d.Poly3DCollection([xz], alpha=0.5, linewidth=1)
# This is the key step to get transparency working
alpha = 0.5
face1.set_facecolor((0, 0, 1, alpha))
face2.set_facecolor((0, 1, 0, alpha))
face3.set_facecolor((1, 0, 0, alpha))
ax.add_collection3d(face1)
ax.add_collection3d(face2)
ax.add_collection3d(face3)
plt.show()
As suggested in the comments, you can divide every plane into its four quadrant planes and draw those individually. This way matplotlib is able to determine which of them should be in front and the planes obey transparency.
A minimal example:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d as mp3d
a = np.array([( 0, 0, 0),( 1, 0, 0),( 1, 1, 0),( 0, 1, 0)])
R1 = np.array([[0,-1,0],[1,0,0],[0,0,1]])
R2 = (R1[::-1].T)[:,[1,0,2]]
R3 = (R1[::-1])[:,[1,0,2]]
f = lambda a,r: np.matmul(r, a.T).T
g = lambda a,r: [a, f(a,r), f(f(a,r),r), f(f(f(a,r),r),r)]
fig = plt.figure()
ax = fig.add_subplot(111, projection=Axes3D.name)
ax.scatter([-1,1], [-1,1], [-1,1], alpha=0.0)
for i, ind , r in zip(range(3),[[0,1,2],[2,0,1],[1,2,0]], [R1,R2,R3]):
xy = g(a[:,ind], r )
for x in xy:
face1 = mp3d.art3d.Poly3DCollection([x] , alpha=0.5, linewidth=1)
face1.set_facecolor((i//2, i%2, i==0, 0.5))
ax.add_collection3d(face1)
plt.show()
I'm struggling to get the axis right:
I've got the x and y values, and want to plot them in a 2d histogram (to examine correlation). Why do I get a histogram with limits from 0-9 on each axis? How do I get it to show the actual value ranges?
This is a minimal example and I would expect to see the red "star" at (3, 3):
import numpy as np
import matplotlib.pyplot as plt
x = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 3)
y = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 3)
xedges = range(5)
yedges = range(5)
H, xedges, yedges = np.histogram2d(y, x)
im = plt.imshow(H, origin='low')
plt.show()
I think the problem is twofold:
Firstly you should have 5 bins in your histogram (it's set to 10 as default):
H, xedges, yedges = np.histogram2d(y, x,bins=5)
Secondly, to set the axis values, you can use the extent parameter, as per the histogram2d man pages:
im = plt.imshow(H, interpolation=None, origin='low',
extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
If I understand correctly, you just need to set interpolation='none'
import numpy as np
import matplotlib.pyplot as plt
x = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 3)
y = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 3)
xedges = range(5)
yedges = range(5)
H, xedges, yedges = np.histogram2d(y, x)
im = plt.imshow(H, origin='low', interpolation='none')
Does that look right?