I found a piece of code which is passing a 1D Numpy array to MatplotLib. The values of array are either 1 or 0, but the graph plotted has colours as yellow or purple. I am unable to find any documentation around it.
Here is the code:
import numpy as np
import matplotlib.pyplot as plt
num_observations = 5000
x1 = np.random.multivariate_normal([0, 0], [[1, .85],[.85, 1]], num_observations) # mean, covariance
x2 = np.random.multivariate_normal([1, 4], [[1, .85],[.85, 1]], num_observations)
features = np.vstack((x1, x2)).astype(np.float32)
labels = np.hstack((np.zeros(num_observations),np.ones(num_observations)))
plt.figure(figsize=(12,8))
plt.scatter(features[:, 0], features[:, 1],
c = labels, alpha = .4)
plt.show()
Can anyone explain how we are getting the colors as yellow and violet? Relevant Documentation would also help.
Its using the default viridis colormap, and so purple represents 0 and yellow represents 1. See here for more about colormaps: https://matplotlib.org/examples/color/colormaps_reference.html.
Adding a colorbar helps here. Adding one to your example is easy:
import numpy as np
import matplotlib.pyplot as plt
num_observations = 5000
x1 = np.random.multivariate_normal([0, 0], [[1, .85],[.85, 1]], num_observations) # mean, covariance
x2 = np.random.multivariate_normal([1, 4], [[1, .85],[.85, 1]], num_observations)
features = np.vstack((x1, x2)).astype(np.float32)
labels = np.hstack((np.zeros(num_observations),np.ones(num_observations)))
plt.figure(figsize=(12,8))
p = plt.scatter(features[:, 0], features[:, 1],
c = labels, alpha = .4)
plt.colorbar(p)
plt.show()
Related
I want to correlate geometry of surfaces with the target variable. In tutorials on scikit learn or tensorflow and so on some routine features are evaluated. For example relation between price of house in Boston with some other features like numbers of rooms, neighborhood and so on.
In my work I have some coordinates in 3D space (x, y and z) representing surfaces. Then, I want to find out how the arrangement of this points can affect the target variable. I very much appreciate if anyone can propose me maybe especial types of ML methods in python that can do so. I have uploaded a view on two simple surfaces created. Then, I want to correlate depth (z values) of surfaces with an arbitrary target. For each surface I may have hundreds of points i.e. z values.
Follwong code makes the fig:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
%matplotlib qt5
x_s_up = np.array([[1, 1, 1], [2, 2, 2]])
y_s_up = np.array([[1, 2, 3], [1, 2, 3]])
z_s_up = np.array([[5, 5, 5], [5.1, 5.2, 5.1]])
x_s_d = np.array([[1, 1, 1], [2, 2, 2]])
y_s_d = np.array([[1, 2, 3], [1, 2, 3]])
z_s_d = np.array([[3.9, 4., 3.8], [4.1, 4.1, 4.2]])
fig = plt.figure()
ax = fig.add_subplot (111, projection="3d")
ax.plot_surface(x_s_up, y_s_up, z_s_up, color='b') # upper surface
ax.plot_surface(x_s_d, y_s_d, z_s_d, color='r') # lower surface
ax.set_xlabel('X'); ax.set_ylabel('Y'); ax.set_zlabel('Z')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import math
na = 400
ma = [2, 1]
Sa = [[3, -2], [-2, 3]]
sigma1 = [3, 3]
nb = 400
mb = [8, 6]
Sb = [[3, -2], [-2, 3]]
xa, ya = np.random.multivariate_normal(ma, Sa, na).T
xb, yb = np.random.multivariate_normal(mb, Sb, nb).T
plt.plot(xa, ya, 'x')
plt.plot(xb, yb, 'x')
plt.axis('equal')
plt.show()
I have randomly generated data from 2-dimensional Gaussian Distributions and need to project this on w=[0, 1] and plot the histogram. I tried using plt.hist but it does not allow the multiplication.
Below links may be useful for learning numpy.
https://docs.scipy.org/doc/numpy-1.15.0/user/basics.creation.html
https://jakevdp.github.io/PythonDataScienceHandbook/02.02-the-basics-of-numpy-arrays.html
I think what you are asking is the below:
w = np.array([2,1])
a = np.array([xa,ya]).T
b = np.array([xb,yb]).T
aw = np.dot(a,w)
bw = np.dot(b,w)
plt.figure(0)
plt.hist(aw,label='a',histtype='step')
plt.hist(bw,label='b',histtype='step')
plt.title('projected')
plt.legend()
I am displaying information with two y-axes and a common x-axis using the following script.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
#creating a host plot with x and y axis
hostplot = host_subplot(111, axes_class=AA.Axes)
#creating a second y axis
extra_y_axis = hostplot.twinx()
extra_y_axis.set_navigate_mode(True)
extra_y_axis.set_navigate(True)
print extra_y_axis.can_zoom() #prints true on output
hostplot.set_xlabel("host_x")
hostplot.set_ylabel("host_y")
extra_y_axis.set_ylabel("extra_y")
hostplot.plot([0, 1, 2], [0, 1, 2])
extra_y_axis.plot([0, 1, 2], [0, 3, 2])
plt.draw()
plt.show()
After this I used the 'Zoom to Rectangle' tool from the tray in the bottom-left as shown below:
.
And I got the following output:
.
Please notice the y-axis scales in both the images. While the zoom functionality is working correctly for the host plot, I am unable to get the extra_y_axis to rescale and it just maintains a constant scale throughout (so I can't really zoom in on plots using the second axis).
How can I make it so that all the axes are rescaled on zooming in a small portion?
Thanks
I've traced down your problem to the sue of the axes_grid1 toolkit. If you don't require the use of this toolkit you can easily fix your issue by initialising your figure in the usual manner:
import matplotlib.pyplot as plt
#creating a host plot with x and y axis
fig, hostplot = plt.subplots()
#creating a second y axis
extra_y_axis = hostplot.twinx()
hostplot.set_xlabel("host_x")
hostplot.set_ylabel("host_y")
extra_y_axis.set_ylabel("extra_y")
hostplot.plot([0, 1, 2], [0, 1, 2])
extra_y_axis.plot([0, 1, 2], [0, 3, 2])
plt.show()
If you do want to use the toolkit then you have to add a couple of lines to get the two y axes to scale and transform together:
import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
fig = plt.figure()
ax1 = SubplotHost(fig, 1, 1, 1)
#set the scale difference between the two y axes
aux_trans = mtransforms.Affine2D().scale(sx = 1.,sy= 1.5)
ax2 = ax1.twin(aux_trans)
fig.add_subplot(ax1)
ax1.plot([0, 1, 2], [0, 1, 2])
ax2.plot([0, 1, 2], [0, 3, 2])
ax1.set_ylim(0,3)
plt.show()
points with label is usually presented in X, y form
X is a multi-dimensional array, y is label/class that belongs to each point of X
what I want to do:
import matplotlib.pyplot as plt
import numpy as np
X = [[0,1],[1,2],[2,3],[3,4]]
X = np.array(X)
y = np.array([0,0,1,2])
myCmap = np.array(['r', 'g', 'b'])
myLabelMap = np.array(['car', 'bicycle', 'plane'])
plt.scatter(X[:, 0], X[:, 1], color=myCmap[y], label=myLabelMap[y])
plt.legend(loc='upper right')
plt.show()
however this will mess up the legend, as you can see in legend section it plot all labels for all points.
Is there a way to solve this without put the X into different arrays?
First you find out the unique labels, and the points they refer to. You then plot those points with the labels, and the others without labels:
import matplotlib.pyplot as plt
import numpy as np
X = [[0,1],[1,2],[2,3],[3,4]]
X = np.array(X)
y = np.array([0,0,1,2])
myCmap = np.array(['r', 'g', 'b'])
myLabelMap = np.array(['car', 'bicycle', 'plane'])
y_unique,id_unique = unique(y,return_index=True)
X_unique = X[id_unique]
X = asarray(X,dtype=float)
for j,yj in enumerate(y_unique):
plt.scatter(X_unique[j, 0], X_unique[j, 1], color=myCmap[yj], label=myLabelMap[yj])
X[id_unique] = nan
plt.scatter(X[:, 0], X[:, 1], color=myCmap[y])
plt.legend(loc='upper right')
plt.show()
See also this question.
How can we plot 2D math vectors with matplotlib? Does anyone have an example or suggestion about that?
I have a couple of vectors stored as 2D numpy arrays, and I would like to plot them as directed edges.
The vectors to be plotted are constructed as below:
import numpy as np
# a list contains 3 vectors;
# each list is constructed as the tail and the head of the vector
a = np.array([[0, 0, 3, 2], [0, 0, 1, 1], [0, 0, 9, 9]])
Edit:
I just added the plot of the final answer of tcaswell for anyone interested in the output and want to plot 2d vectors with matplotlib:
The suggestion in the comments by halex is correct, you want to use quiver (doc), but you need to tweak the properties a bit.
import numpy as np
import matplotlib.pyplot as plt
soa = np.array([[0, 0, 3, 2], [0, 0, 1, 1], [0, 0, 9, 9]])
X, Y, U, V = zip(*soa)
plt.figure()
ax = plt.gca()
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)
ax.set_xlim([-1, 10])
ax.set_ylim([-1, 10])
plt.draw()
plt.show()
It's pretty straightforward. Hope this example helps.
import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(10,5,100)
y = 3 + .5*x + np.random.normal(0,1,100)
myvec = np.array([x,y])
plt.plot(myvec[0,],myvec[1,],'ro')
plt.show()
Will produce:
To plot the arrays you can just slice them up into 1D vectors and plot them. I'd read the full documentation of matplotlib for all the different options. But you can treat a numpy vector as if it were a normal tuple for most of the examples.