[Scatter plot, 3D plot and regression plane] Plotly dynamic visualization [python, scatter, 3D, surface, pair, joint]

33dd.gif

python==3.8 plotly==4.10.0

Article to play with options by referring to the official gallery

scatter (scatter plot)

Basic

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", title="iris scatter plot")
fig.show()

image.png

Split

Separate drawings to draw with facet Specify row and col from add_trace to decide which drawing to overwrite

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species",
                 title="Add line subplot")

reference_line = go.Scatter(x=[2, 4],
                            y=[4, 8],
                            mode="lines",
                            line=go.scatter.Line(color="gray"),
                            showlegend=False)

fig.add_trace(reference_line, row=1, col=1)
fig.add_trace(reference_line, row=1, col=2)
fig.add_trace(reference_line, row=1, col=3)

fig.show()

image.png

Overwrite different types of graph objects

from plotly.subplots import make_subplots

fig = make_subplots(rows=1, cols=2)

fig.add_scatter(y=[4, 2, 3.5], mode="markers",
                marker=dict(size=20, color="LightSeaGreen"),
                name="a", row=1, col=1)

fig.add_bar(y=[2, 1, 3],
            marker=dict(color="MediumPurple"),
            name="b", row=1, col=1)

fig.add_scatter(y=[2, 3.5, 4], mode="markers",
                marker=dict(size=20, color="MediumPurple"),
                name="c", row=1, col=2)

fig.add_bar(y=[1, 3, 2],
            marker=dict(color="LightSeaGreen"),
            name="d", row=1, col=2)

fig.show()

image.png

Change size depending on the size of the value (bubble)

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
                 size='petal_length')
fig.show()

image.png

Shake the text dot by dot

import plotly.express as px
fig = px.scatter(df, x="sepal_length", y="sepal_width", text="species", size_max=60)

fig.update_traces(textposition='top center')

fig.update_layout(
    height=800,
    title_text='iris label'
)

fig.show()

image.png

join plot in scatter

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", marginal_y="violin",
           marginal_x="box", trendline="ols", template="simple_white")
fig.show()

image.png

pair plot

import plotly.express as px
df = px.data.iris()
fig = px.scatter_matrix(df, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species")
fig.show()

image.png

3d scatter

import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
                    color='petal_length', symbol='species')
fig.show()

image.png

Add a surface (surface)

import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from sklearn.svm import SVR

df = px.data.iris()

#Make a map from X

margin = 0
X = df[['sepal_width', 'sepal_length']]
y = df['petal_width']
model = SVR(C=1.)
model.fit(X, y)

#Details(mesh,grid)Occurs

mesh_size = .02
x_min, x_max = X.sepal_width.min() - margin, X.sepal_width.max() + margin
y_min, y_max = X.sepal_length.min() - margin, X.sepal_length.max() + margin
xrange = np.arange(x_min, x_max, mesh_size)
yrange = np.arange(y_min, y_max, mesh_size)
xx, yy = np.meshgrid(xrange, yrange)

#Predict for all points on the mesh

pred = model.predict(np.c_[xx.ravel(), yy.ravel()])
pred = pred.reshape(xx.shape)

#Plot the original point, then x1,x2 grid plane pushed up by z
#A surface is drawn using a surface that connects all the points.

fig = px.scatter_3d(df, x='sepal_width', y='sepal_length', z='petal_width')
fig.update_traces(marker=dict(size=5))
fig.add_traces(go.Surface(x=xrange, y=yrange, z=pred, name='pred_surface'))
fig.show()

image.png

You can also display contour lines of a 3D graph on the axis with prjection Z.

fig = go.Figure(data=[go.Surface(z=pred)])
fig.update_traces(contours_z=dict(show=True, usecolormap=True,
                                  highlightcolor="limegreen", project_z=True))

fig.show()

image.png

Contour lines in plan view

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Contour(
    z=pred,
    colorscale="Cividis",
))

fig.show()

image.png

Visualize the learning process

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Contour(
    z=pred,
    colorscale="Cividis",
))

fig.add_trace(
    go.Scatter(
        x=[20,40,60,70,80,100,90,80],
        y=[20,40,80,100,120,140,160,160],
        mode="markers+lines",
        name="steepest",
        line=dict(
            color="red"
        )
    )
)


fig.show()

image.png

You can replace the model

from sklearn.linear_model import LinearRegression

model_LR = LinearRegression()
model_LR.fit(X, y)


pred_LR = model_LR.predict(np.c_[xx.ravel(), yy.ravel()])
pred_LR = pred_LR.reshape(xx.shape)

fig = px.scatter_3d(df, x='sepal_width', y='sepal_length', z='petal_width',color='species')
fig.update_traces(marker=dict(size=5))
fig.add_traces(go.Surface(x=xrange, y=yrange, z=pred_LR, name='pred_LR_surface',colorscale='Viridis'))
fig.show()

33dd.gif

Other

type = line

Make a stacked area graph by setting scatter as type = line and specifying stack

import plotly.graph_objects as go

x=['Winter', 'Spring', 'Summer', 'Fall']

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=x, y=[30, 30, 30, 30],
    hoverinfo='x+y',
    mode='lines',
    line=dict(width=0.5, color='rgb(131, 90, 1)'),
        stackgroup='one'
))
fig.add_trace(go.Scatter(
    x=x, y=[20, 20, 20, 20],
    hoverinfo='x+y',
    mode='lines',
    line=dict(width=0.5, color='rgb(111, 1, 219)'),
        stackgroup='one'
))
fig.add_trace(go.Scatter(
    x=x, y=[10, 10, 10, 10],
    hoverinfo='x+y',
    mode='lines',
    line=dict(width=0.5, color='rgb(1, 247, 212)'),
        stackgroup='one'
))

fig.update_layout(yaxis_range=(0, 100))
fig.show()

image.png

Area is easy to do from px

import plotly.express as px

fig = px.area(x=['Winter', 'Spring', 'Summer', 'Fall'], 
              y=[[30, 30, 30, 30],
                [20, 20, 20, 20],
                [10, 10, 10, 10]]
             )
fig.update_layout(yaxis_range=(0, 100))
fig.show()

image.png

When specifying area in the data frame

df = px.data.stocks()
fig = px.area(df,x='date', y=df.columns[1:6], title="6 company stocks plot")
fig.show()

image.png

Also line_3d

import plotly.express as px
df = px.data.gapminder().query("country=='Brazil'")
fig = px.line_3d(df, x="gdpPercap", y="pop", z="year")
fig.show()

image.png

that's all

Recommended Posts

[Scatter plot, 3D plot and regression plane] Plotly dynamic visualization [python, scatter, 3D, surface, pair, joint]
[Visualization of ratio] Plotly and dynamic visualization [python, pie, sunburst, sanky, treemap, fannele,]
[Density visualization] Plotly and dynamic visualization [python3, hist, kde, join, contour, heat map]
[Drawing and labeling multiple graphs] Plotly dynamic visualization [python3, make subplot, xlabel, ylabel]
[EDA super basic] Plotly and dynamic visualization [python3, table, bar, box, violin, joy]
[Various image analysis with plotly] Dynamic visualization with plotly [python, image]
[Write to map with plotly] Dynamic visualization with plotly [python]
Create 3D scatter plot with SciPy + matplotlib (Python)
Solving with Ruby and Python AtCoder ABC178 D Dynamic programming