I want to add constant x, y, z lines into a matplotlib 3D scatter plot in Python which extended from this limit point, may I know how could I do so?
x_limit = [-0.5] y_limit = [151] z_limit = [1090]
Example code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pandas as pd
from scipy.stats import multivariate_normal
fig = plt.figure(figsize=(8,8)) # size 4 inches X 4 inches
ax = fig.add_subplot(111, projection='3d')
np.random.seed(42)
xs = np.random.random(100)*-0.8
ys = np.random.random(100)*300
zs = np.random.random(100)*10500
plot = ax.scatter(xs,ys,zs)
ax.set_title("3D plot with limit")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
x_limit = [-0.5]
y_limit = [151]
z_limit = [1090]
ax.scatter(x_limit, y_limit, z_limit, c = 'g', marker = "s", s = 50)
plt.show()
This code should do the trick. There are a couple important things to note though. First, the mesh grid created only worked because each of the three axes share the same limits. Second, while the x_limit and y_limit values work as the X and Y arguments it appears that the Z argument is expected to be of a higher dimensionality (hence why I used full_like to fill an array of the same shape as x_1 and x_2 with the Z limit).
x_1, x_2 = np.meshgrid(np.arange(0, 1.1, 0.1), np.arange(0, 1.1, 0.1))
ax.plot_surface(x_limit, x_1, x_2, color='r', alpha=0.5)
ax.plot_surface(x_1, y_limit, x_2, color='g', alpha=0.5)
ax.plot_surface(x_1, x_2, np.full_like(x_1, z_limit), color='b', alpha=0.5)
I'm using matplotlib 3.3.4 and generating a basic contour plot. But when I do so, the X and Y axis labels are showing my desired range (e.g. 0 to pi) but there's also an extra set of labels showing up that appear to be some sort of normalized values (0 to 1). The following code reproduces this:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, np.pi, 40)
y = np.linspace(0, np.pi, 40)
z = np.sin(x[:, None])**2 + np.sin(y)**2
fig, ax = plt.subplots(figsize=(10,10))
ax = fig.add_subplot(111)
ax.contour(x, y, z)
and produces a plot like the one below. I see axis labels at the expected values [0, 0.5, 1.0, 1.5, 2.0, 2.5, and 3.0]. But there's another set [0, 0.2, 0.4, 0.6, 0.8, 1.0] that's coming from somewhere.
After reviewing the contour() example at Contour Example I realize I should probably be calling np.meshgrid() rather than doing the extra axis stuff to produce z above.
Any clues as to what is causing this odd axis label behavior?
You're adding two subplots, one via plt.subplots, and one via add_subplot. Remove one of them and the figure will only have one set of ticks:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, np.pi, 40)
y = np.linspace(0, np.pi, 40)
z = np.sin(x[:, None])**2 + np.sin(y)**2
fig, ax = plt.subplots(figsize=(10,10))
ax.contour(x, y, z)
I'm able to plot a surface in 3d in matplotlib, but I also need to plot a line, and a point on the surface. The surface that the line are fine, but the point does not show up on the surface for some reason, though. Here is the code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-2.0, 2.0, 0.05)
Y = np.arange(-1.0, 3.0, 0.05)
X, Y = np.meshgrid(X, Y)
Z = (np.ones([np.shape(X)[0],np.shape(X)[1]])-X)**2+100*(Y-(X)**2)**2
Gx, Gy = np.gradient(Z) # gradients with respect to x and y
G = (Gx**2+Gy**2)**.5 # gradient magnitude
N = G/G.max() # normalize 0..1
surf = ax.plot_surface(
X, Y, Z, rstride=1, cstride=1,
facecolors=cm.jet(N),
linewidth=0,
antialiased=False,
shade=False)
plt.hold(True)
ax.hold(True)
# add the unit circle
x_1 = np.arange(-1.0, 1.0, 0.005)
x_2 = np.arange(-1.0, 1.0, 0.005)
y_1 = np.sqrt(np.ones(len(x_1)) - x_1**2)
y_2 = -np.sqrt(np.ones(len(x_2)) - x_2**2)
x = np.array(x_1.tolist() + x_2.tolist())
y = np.array(y_1.tolist() + y_2.tolist())
z = (np.ones(len(x))-x)**2+100*(y-(x)**2)**2
ax.plot(x, y, z, '-k')
plt.hold(True)
ax.hold(True)
ax.scatter(np.array([0.8]),
np.array([0.6]),
np.array([0.045]),
color='red',
s=40
)
# Get current rotation angle
print 'rotation angle is ', ax.azim
# Set rotation angle to 60 degrees
ax.view_init(azim=60)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
The issue is that the point does not show up on the surface. Now, when I replace this code:
ax.scatter(np.array([0.8]),
np.array([0.6]),
np.array([0.045]),
color='red',
s=40
)
...with this code (i.e. just adding to the last value)...
ax.scatter(np.array([0.8]),
np.array([0.6]),
np.array([0.045+800]),
color='red',
s=40
)
...then it shows up. But I can't think of a reason why it is not showing up when I want to plot the actual value in the surface. Does someone know how to fix this?
(As an aside, I'd love to get rid of the weird line in the middle of the unit circle that I plot on the surface. I can't seem to get rid of it.)
Much obliged!
For an upcoming assignment I am require to make a series of diagrams that have two graphs that have a line going across from one graph to the other, colouring an area below that line on the other graph.
As shown in this rough drawing:
This is what I currently have:
From this code:
from matplotlib import pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.plot([0,1,2,3,4,5,6,7,8,9,10], [1,1,1,1,1,0,0,0,0,0,0], '-b')
ax1.plot([0,1,2,3,4,5,6,7,8,9,10], [0,0,0,0,0,1,1,1,1,1,1], '-r')
ax1.set_ylim([0, 1.2])
ax2 = fig.add_subplot(122)
ax2.plot([0,5,10,15,20,25,30,35,40], [1,1,1,1,0,0,0,0,0], '-b')
ax2.plot([0,5,10,15,20,25,30,35,40], [0,0,0,0,1,1,1,1,1], '-r')
ax2.set_ylim([0, 1.2])
plt.show()
Obviously this only generates the two graphs and I have yet been unable to add the line across the two graphs.
I really want to be able to do this with Matplotlib in python with the ability to change the value (45 in the example case) and the coloured area change automatically.
Thanks!
There are three steps: 1st, find the intercept point between green and blue lines in the left panel. 2nd, find the intercept point between the red and lines in the right panel. 3rd, fill the area between. These steps involves np.interp scipy.interpolat scipy.optimize and plt.fill_between, which you should look up.
from matplotlib import pyplot as plt
import numpy as np
import scipy.interpolate as spinp
import scipy.optimize as spop
fig = plt.figure(figsize=(16,4))
ax1 = fig.add_subplot(121)
x = [0,10,20,30,40,50,60,70,80,90,100]
yr = [1,1,1,1,1,0,0,0,0,0,0]
yg = [0,0,0,0,0,1,1,1,1,1,1]
turn_pt = np.interp(45, x, yr) #change 45 to whatever.
yb = [0.,turn_pt,turn_pt]
ax1.plot(x, yr, '-r')
ax1.plot(x, yg, '-g')
xb = [45, 45, 200]
ll = plt.plot(xb,yb, '-b')
ll[0].set_clip_on(False)
plt.axis([0,100,0,1.2])
#the above three lines to draw the line out of the box.
ax2 = fig.add_subplot(122)
yr = [1,1,1,1,0,0,0,0,0]
yg = [0,0,0,0,1,1,1,1,1]
x = [0,5,10,15,20,25,30,35,40]
brk_pt_f = lambda X, V: (spinp.interp1d(x, yr)(X)-V)**2
brk_pt = spop.fmin(brk_pt_f, 17., args=(turn_pt,), disp=0) #17. is you inital guess,
#the above two lines solve for the intersection between the blue line and the red line
zero_pt = 20.
start_pt= 0.
xb = np.hstack((start_pt, brk_pt, zero_pt))
yb = [turn_pt,turn_pt,0]
ax2.plot(x, yr, '-r')
ax2.plot(x, yg, '-g')
ax2.plot(xb, yb, '-b')
ax2.hlines(turn_pt,0, 40, 'b', alpha=0.)
ax2.fill_between(xb, yb, 0, alpha=0.4)
ax2.set_ylim([0, 1.2])
ax2.set_xlim([0, 40])
There are a few solutions to get rid of the top x-axis and the right y-axis, please search older SO posts.
And finally, welcome to SO.
Is there a function in matplotlib similar to MATLAB's line extensions?
I am basically looking for a way to extend a line segment to a plot. My current plot looks like this.
After looking at another question and applying the formula, I was able to get it to here, but it still looks messy.
Does anyone have the magic formula here?
Have a go to write your own as I don't think this exists in matplotlib. This is a start, you could improve by adding the semiinfinite etc
import matplotlib.pylab as plt
import numpy as np
def extended(ax, x, y, **args):
xlim = ax.get_xlim()
ylim = ax.get_ylim()
x_ext = np.linspace(xlim[0], xlim[1], 100)
p = np.polyfit(x, y , deg=1)
y_ext = np.poly1d(p)(x_ext)
ax.plot(x_ext, y_ext, **args)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
return ax
ax = plt.subplot(111)
ax.scatter(np.linspace(0, 1, 100), np.random.random(100))
x_short = np.linspace(0.2, 0.7)
y_short = 0.2* x_short
ax = extended(ax, x_short, y_short, color="r", lw=2, label="extended")
ax.plot(x_short, y_short, color="g", lw=4, label="short")
ax.legend()
plt.show()
I just realised you have some red dots on your plots, are those important? Anyway the main point I think you solution so far is missing is to set the plot limits to those that existed before otherwise, as you have found, they get extended.
New in matplotlib 3.3
There is now an axline method to easily extend arbitrary lines:
Adds an infinitely long straight line. The line can be defined either by two points xy1 and xy2
plt.axline(xy1=(0, 1), xy2=(1, 0.5), color='r')
or defined by one point xy1 and a slope.
plt.axline(xy1=(0, 1), slope=-0.5, color='r')
Sample data for reference:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.default_rng(123).random((2, 100)) * 2 - 1
m, b = -0.5, 1
plt.scatter(x, y, c=np.where(y > m*x + b, 'r', 'k'))