Plotly using Python - colors

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.

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

Python Plotly Scatter Plot on 3D Mesh

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()

How to add a regression line for the entire data in seaborn.lmplot?

I'm trying to plot the scatter plot in which each point is colored w.r.t the variable Points. Moreover, I want to add the regression line.
import pandas as pd
import urllib3
import seaborn as sns
decathlon = pd.read_csv("https://raw.githubusercontent.com/leanhdung1994/Deep-Learning/main/decathlon.txt", sep='\t')
g = sns.lmplot(
data = decathlon,
x="100m", y="Long.jump",
hue = 'Points', palette = 'viridis'
)
It seems to me that there are 2 regression lines, one for each group of the data. This is not what I want. I would like to have a regression line for the entire data. Moreover, how can I hide the legend on the right hand side?
Could you please elaborate on how to do so?
You should not use lmplot unless you need to use a FacetGrid to split your dataset in several subplots.
Since the example that you show does not use any of the functionalities provided by FacetGrid, you should instead create your plot using a combination of scatterplot() and regplot()
tips = sns.load_dataset('tips')
ax = sns.scatterplot(data=tips, x="total_bill", y="tip", hue="day")
sns.regplot(data=tips, x="total_bill", y="tip", scatter=False, ax=ax)

Using "hue" for a Seaborn visual: how to get legend in one graph?

I created a scatter plot in seaborn using seaborn.relplot, but am having trouble putting the legend all in one graph.
When I do this simple way, everything works fine:
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
df2 = df[df.ln_amt_000s < 700]
sns.relplot(x='ln_amt_000s', y='hud_med_fm_inc', hue='outcome', size='outcome', legend='brief', ax=ax, data=df2)
The result is a scatter plot as desired, with the legend on the right hand side.
However, when I try to generate a matplotlib figure and axes objects ahead of time to specify the figure dimensions I run into problems:
a4_dims = (10, 10) # generating a matplotlib figure and axes objects ahead of time to specify figure dimensions
df2 = df[df.ln_amt_000s < 700]
fig, ax = plt.subplots(figsize = a4_dims)
sns.relplot(x='ln_amt_000s', y='hud_med_fm_inc', hue='outcome', size='outcome', legend='brief', ax=ax, data=df2)
The result is two graphs -- one that has the scatter plots as expected but missing the legend, and another one below it that is all blank except for the legend on the right hand side.
How do I fix this such? My desired result is one graph where I can specify the figure dimensions and have the legend at the bottom in two rows, below the x-axis (if that is too difficult, or not supported, then the default legend position to the right on the same graph would work too)? I know the problem lies with "ax=ax", and in the way I am specifying the dimensions as matplotlib figure, but I'd like to know specifically why this causes a problem so I can learn from this.
Thank you for your time.
The issue is that sns.relplot is a "Figure-level interface for drawing relational plots onto a FacetGrid" (see the API page). With a simple sns.scatterplot (the default type of plot used by sns.relplot), your code works (changed to use reproducible data):
df = pd.read_csv("https://vincentarelbundock.github.io/Rdatasets/csv/datasets/iris.csv", index_col=0)
fig, ax = plt.subplots(figsize = (5,5))
sns.scatterplot(x = 'Sepal.Length', y = 'Sepal.Width',
hue = 'Species', legend = 'brief',
ax=ax, data = df)
plt.show()
Further edits to legend
Seaborn's legends are a bit finicky. Some tweaks you may want to employ:
Remove the default seaborn title, which is actually a legend entry, by getting and slicing the handles and labels
Set a new title that is actually a title
Move the location and make use of bbox_to_anchor to move outside the plot area (note that the bbox parameters need some tweaking depending on your plot size)
Specify the number of columns
fig, ax = plt.subplots(figsize = (5,5))
sns.scatterplot(x = 'Sepal.Length', y = 'Sepal.Width',
hue = 'Species', legend = 'brief',
ax=ax, data = df)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=handles[1:], labels=labels[1:], loc=8,
ncol=2, bbox_to_anchor=[0.5,-.3,0,0])
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