Python Plotly Scatter Plot on 3D Mesh - python-3.x

I have an STL(mesh) file that I want to render on plotly. I found this library which is using
import plotly.graph_objects as go
the go object of plotly.
and I want to make a scatter plot on the same graph and not sure how to do that.
At the end the problem is using the plotly graph_object with ploty express object together (at least this is the solution that I think can be done. ) If you know how to render a mesh and render some points on it it would be great.
Thank you

You need to add the traces to a single Figure.
For example:
import plotly.graph_objects as go
import numpy as np
pts = np.loadtxt(np.DataSource().open('https://raw.githubusercontent.com/plotly/datasets/master/mesh_dataset.txt'))
x, y, z = pts.T
mesh = go.Mesh3d(x=x, y=y, z=z, color='lightpink', opacity=0.50)
scatter = go.Scatter3d(x=x, y=y, z=z, mode='markers')
fig = go.Figure(data=[mesh, scatter])
fig.show()

Related

plt.legend only adds first element to scatter plot

I am trying to add a legend to my scatter plot with 13 classes, however, with my code below, I am only able to get the first label. Can you assist me in generating the full list to show up in the legend of the scatter plot?
Here is my example code:
from sklearn.datasets import make_blobs
from matplotlib import pyplot
from pandas import DataFrame
# generate 2d classification dataset
X, y = make_blobs(n_samples=1000, centers=13, n_features=2)
classes = [f"class {i}" for i in range(13)]
#fig = plt.figure()
plt.figure(figsize=(15, 12))
scatter = plt.scatter(
x=X[:,0],
y=X[:,1],
s = 20,
c = y,
cmap='Spectral'
#c=[sns.color_palette()[x] for x in y_train_new]
)
plt.gca().set_aspect('equal', 'datalim')
plt.legend(classes)
plt.title('Dataset', fontsize=24)
You can do that by replacing the plt.legend(classes) in your code by this line... I hope this is what you are looking for. I am using matplotlib 3.3.4.
plt.legend(handles=scatter.legend_elements()[0], labels=classes)
Output plot

Plotly using Python

I have 4 nxk matrices to be plotted using scatter plot. I need to set different the color for each 'k'. Is there a way to do so?
the code snippet is as follows:
import plotly.graph_objects as go
fig = fig.add_trace(go.scatter(x, y)
Here, 'y' is my nxk matrix.

Python: Pickle.load function returns the correct 3d-scatter plot, but is not interactive anymore

this is my first question here so let me know if I should make any improvements regarding e.g. formulation of the question, code and so on.
So I am creating several 3-D Scatter Plots in Python and want to safe them for later re usage and comparability. I am using Qt5 as Graphics Backend in Spyder, which perfectly displays my interactive (so I can rotate over the axes and flip the plot) 3-D Scatter plot using the origin Code.
Now I am able to successfully save the created plot and also load it into a new script, which opens the Plot in Qt5 as well. But somehow the interactivity is gone, meaning I am not able to rotate over the axes and flip the plot anymore.
I was unable to find any guidance to that issue or find any person with a similar problem. Do you guys have any idea? I'll put the relevant part of my sample Code below:
""" First script """
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import pickle
testdf = pd.DataFrame({"X" : x, "Y" : y, "Z" : z}) #x and y are the criteria, z the values, stored as lists
# Create 3d scatter plot
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(111, projection="3d")
ax.scatter(x, y, z, c=z, marker="o")
ax.set_xlabel("Initial Notional Cluster")
ax.set_ylabel("Laufzeit in Month Cluster")
ax.set_zlabel("Vol. Weighted Margin")
plt.show()
# Save the figure object as binary file
file = open(r"Init_Lfz_VolWeightedMargin.pkl", "wb")
pickle.dump(fig, file)
file.close()
""" Second script """
import matplotlib.pyplot as plt
figx = pickle.load(open(r"Init_Lfz_VolWeightedMargin.pkl", "rb"))
plt.show()
Any idea, why the interactivity is gone? According to the pickle library and other usercases, this shall not happen.
Many thanks.

Adding pie chart at given coordinates to cartopy projection

I am a beginner in data visualization, and even more with cartopy, I know for most of people my question would be obvious. I am trying to get familiar with cartopy and I successfully plot text and point. But I couldn't achieve it for pie chart.
I just want to plot pie chart on a particular projection. But I am really confuse, despite the documentation of cartopy. I have first try this:
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines(resolution='110m') # 110, 50, 10
ax.stock_img()
lat, long = 30, 30 # the latitude longitude
ax.pie(long, lat, [0.25, 0.75], transform=ccrs.PlateCarree())
That do not work, So I have checked and I found this Cartopy coastlines hidden by inset_axes use of Axes.pie but I do not understand what happend under the hood and furthermore it seems limited to PlateCarre(). I have try to modified it but I do not managed to get it work properly.
So my very simple question is How can I add several pie chart to a specific projection given latitude and longitude? If you can develop your answer you will be really welcome.
You can use an inset_axes to place a new axes into the plot, which will allow to host the pie chart. The position of the inset_axes is determined by the bbox_to_anchor argument. To have this argument use the coordinates of the projection of the cartopy axes (ax), you need to set the bbox_transform=ax.transData.
If you have your coordinates in a different coordinate system, you need to convert them to the one in use using the projection's .transform_point method first.
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines(resolution='110m')
ax.stock_img()
def plot_pie_inset(data,ilon,ilat,ax,width):
ax_sub= inset_axes(ax, width=width, height=width, loc=10,
bbox_to_anchor=(ilon, ilat),
bbox_transform=ax.transData,
borderpad=0)
wedges,texts= ax_sub.pie(data)
ax_sub.set_aspect("equal")
lon,lat = 90,30
lonr,latr = ccrs.Robinson().transform_point(lon,lat, ccrs.PlateCarree())
plot_pie_inset([0.25, 0.75],lonr,latr,ax,0.5)
plt.show()

3D plotting of points

I want to use python to plot some specific points in 3D given their coordinates. I want to use the matplotlib library but I'm not sure if there's an easy way of doing this.
Let's say I want to plot the following points:
(1,0,0)
(2,2,2)
(-1,2,0)
(1,2,1)
Since some of the examples around are overly complicated, a minimal example for a 3D scatter plot in matplotlib would look like this:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig, ax = plt.subplots(subplot_kw=dict(projection='3d') )
points = [(1,0,0), (2,2,2), (-1,2,0), (1,2,1)]
x,y,z = zip(*points)
ax.scatter(x,y,z, s=100)
plt.show()

Resources