[PYTHON] plotly trace and layout templates that are likely to be used in scatter plots

Introduction

It is a template of trace, layout that seems to be used when drawing a scatter plot with plotly Please erase unnecessary parts as appropriate

environment

Mac OS python 3.8.5 plotly 4.12.0

pip

pip install plotly

trace template

import plotly.offline as offline
import plotly.graph_objs as go

import plotly
colors = plotly.colors.DEFAULT_PLOTLY_COLORS
"""
Get default color
['rgb(31, 119, 180)', 'rgb(255, 127, 14)', 'rgb(44, 160, 44)', 'rgb(214, 39, 40)', 'rgb(148, 103, 189)',
 'rgb(140, 86, 75)', 'rgb(227, 119, 194)', 'rgb(127, 127, 127)', 'rgb(188, 189, 34)', 'rgb(23, 190, 207)']
"""

from plotly.validators.scatter.marker import SymbolValidator
raw_symbols = SymbolValidator().values
"""
Values that can be used for marker symbols
[0, '0', 'circle', 100, '100', 'circle-open',...
There are 474
https://plotly.com/python/marker-style/#custom-marker-symbols
"""
data = []
trace = go.Scatter(
    x=[i for i in range(10)],
    y=[i for i in range(10)],
    yaxis="y1",  #yth?axis"y2", "y3", "y4", .. https://plotly.com/python/multiple-axes/#multiple-axes
    line=dict(color=colors[0], width=6, dash="dashdot"),
    # dash="dash", "dot" or "dashdot" https://plotly.com/python/line-charts/#style-line-plots

    line_shape="hv",
    #Step etc."hv", "vh", "hvh", "vhv", "spline", "liner" https://plotly.com/python/legend/#hiding-the-trace-initially

    marker=dict(color=colors[0], size=10, line=dict(color="red", width=2)),
    # line=Marker contour information https://plotly.com/python/marker-style/#add-marker-border

    mode="lines+markers",
    # "lines", "lines+markers" or "markers" https://plotly.com/python/line-charts/#line-plot-modes

    marker_symbol=raw_symbols[0],  #Specify the shape of the marker https://plotly.com/python/marker-style/#custom-marker-symbols
    name="sample",  #Used in the legend
    hovertemplate="y: %{y}<br>x: %{x}",
    opacity=1,  #Transparency 0~1 https://plotly.com/python/marker-style/#color-opacity
    visible=True,  # True, False or legendonly
    showlegend=True,  #Legend display True or False
    legendgroup="sample"  #Traces with the same string are displayed/Hidden toggle syncs https://plotly.com/python/legend/#grouped-legend-items
)
data.append(trace)

layout template

Basic

title, xaxis, etc. For the time being, if you have this, you can format the graph layout

layout = go.Layout(
    title=dict(text='<b>sample title</b><br>text', font=dict(size=16)),
    xaxis=dict(title=dict(text='x axis label', font=dict(size=12)), tickfont=dict(size=12), autorange=True),
    # https://plotly.com/python/reference/layout/xaxis/
    
    yaxis=dict(title='y axis label'),
    font=dict(size=16),  #Global font
    newshape=dict(line=dict(color="cyan", width=4, dash="solid")),
    # dash='solid', 'dot', 'dash', 'longdash', 'dashdot','longdashdot'
    autosize=True,
    showlegend=True, )

fig = dict(data=data, layout=layout)

offline.plot(fig, include_plotlyjs="cdn", auto_open=True, filename='sample plotly.html', config={
    'modeBarButtonsToAdd': ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect', 'eraseshape']}, )

title=dict(text='<b>sample title</b><br>text' You can use html tags in the string part, bold with <b> str </ b>, line break with <br> If you want to color it in bold, such as <b style =" color: red "> test </ b>

Added a button to draw a line or circle in the upper right corner on the last line config={'modeBarButtonsToAdd': ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect', 'eraseshape']}

2nd axis

Set yaxis =" y2 " in trace

Where yaxis2 =

layout = go.Layout(
    title=dict(text='<b>sample title</b><br>text', font=dict(size=16)),
    xaxis=dict(title=dict(text='x axis label', font=dict(size=12)), tickfont=dict(size=12), tickangle=0),
    # https://plotly.com/python/reference/layout/xaxis/

    yaxis=dict(title="y axis label"),  #Same as xaxis
    yaxis2=dict(title="y2 axis label", overlaying="y", side="right", showgrid=False),
    font=dict(size=16),  #Global font
    newshape=dict(line=dict(color="cyan", width=4, dash="solod")),
    # dash='solid', 'dot', 'dash', 'longdash', 'dashdot','longdashdot'
    autosize=True,
    showlegend=True, )

fig = dict(data=data, layout=layout)

offline.plot(fig, include_plotlyjs="cdn", auto_open=True, filename='sample plotly.html', config={
    'modeBarButtonsToAdd': ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect', 'eraseshape']}, )

Other things to use

When you want to change the font format of title, xaxis, when you want to decide the range of xaxis, when you want to change other things such as hover and spikes

layout = go.Layout(
    title=dict(text='<b>sample title</b><br>text', font=dict(family="Arial", size=16, color="black")),
    xaxis=dict(title=dict(text='x axis label', font=dict(family="Arial", size=12, color="black")),
               tickfont=dict(family="Arial", size=12, color="black"), type="-", tick0=0, dtick=1, range=[0, 100],
               autorange=True, rangemode="normal", tickangle=0, tickformat="", color="white", showspikes=True,
               spikemode="toaxis", spikecolor="red", domain=[0, 1]),  # https://plotly.com/python/reference/layout/xaxis/

    yaxis=dict(title='y axis label', spikemode="toaxis", domain=[0, 1]),  #Same as xaxis
    font=dict(family="Arial", size=16, color="black"),  #Global font
    legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),  # orientation=h Display legend horizontally
    newshape=dict(line=dict(color="cyan", width=4, dash="dashdot")),
    # dash='solid', 'dot', 'dash', 'longdash', 'dashdot','longdashdot'

    hovermode='x unified',  # "x", "y", "closest", False, "x unified", "y unified"
    hoverlabel=dict(font=dict(family="Arial", size=20, color="black"), bgcolor="white", bordercolor="black"),
    # paper_bgcolor="#ffffff",  #Color specification outside the plot
    # plot_bgcolor="#ffffff",  #Color specification in the plot
    # template="plotly_dark",  #Template https://plotly.com/python/templates/
    autosize=True,
    showlegend=True, )

fig = dict(data=data, layout=layout)

offline.plot(fig, include_plotlyjs="cdn", auto_open=True, filename='sample plotly.html', config={
    'modeBarButtonsToAdd': ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect', 'eraseshape']}, )

xaxis yaxis Specify the font format, size, and color with font = dict (family =" Arial ", size = 16, color =" black ")

family="Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman".

Specify the font of the axis value with tickfont = dict (family =" Arial ", size = 12, color =" black ") type ="-": Change to time axis or log scale depending on the input value

"-" | "linear" | "log" | "date" | "category" | "multicategory" Default: "-"

tick0: Specify the minimum value of the axis dtick: Axis scale interval specification range = [min, max]: Specify the maximum / minimum of the axis to be displayed ʻAutorange = True`: Automatically sets the range according to the given value, becomes False when range is entered

( True | False | "reversed" )

rangemode: normal: The axis range is determined by the input value, tozero: 0 is the origin, nonnefative: non-negative

Type: enumerated , one of ( "normal" | "tozero" | "nonnegative" ) Default: "normal"

tickangle: Axis value display angle, default is" auto " tickformat: When you want to display% etc., the default is " " color: color specification of axis (both label and tick) show spikes: Show / hide spikes (dotted line that appears when you move the cursor closer to the plot) spikemode: Change how spikes are displayed

Type: flaglist string. Any combination of "toaxis", "across", "marker" joined with a "+" Examples: "toaxis", "across", "toaxis+across", "toaxis+across+marker" Default: "toaxis"

spikecolor: Spike color domain: Specify graph area, default [0, 1], range 0 ~ 1

legend orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1 Turn the legend sideways. Align the lower right with the graph coordinates y = 1.02, x = 1. The coordinates are (x, y) = (0, 0) at the bottom left of the graph (blue part inside the axis) and (x, y) = (1, 1) at the top right.

hovermode Change the display method of the value when the cursor is moved closer to the plot

"x", "y", "closest", False, "x unified", "y unified"

Other

paper_bgcolor: Color specification outside the plot plot_bgcolor: Color specification in the plot template: Graph template,"plotly_dark"is cool https://plotly.com/python/templates/

Time axis

The x-axis value must be set to time such as datetime

layout = go.Layout(
    title="sample",
    xaxis=dict(title="time", type="date", rangeslider=dict(visible=True), tickformat="%Y/%m/%d %H:%M:%S",
               dtick=86400000.0 / 24),
    yaxis=dict(title='y axis label'),
    font=dict(size=16),
    newshape=dict(line=dict(color="cyan", width=4, dash="solid")),
    hovermode='x unified',
    hoverlabel=dict(font=dict(size=20)),
    autosize=True,
    showlegend=True)

fig = dict(data=data, layout=layout)

offline.plot(fig, include_plotlyjs="cdn", auto_open=True, filename='sample plotly2.html', config={
    'modeBarButtonsToAdd': ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect', 'eraseshape']}, )

type =" date ": Change to time axis rangeslider = dict (visible = True): Added a slider below the graph to change the display range of the graph. tickformat: Specify the time display format

"%Y/%m/%d %H:%M:%S" = yyyy/mm/dd HH:MM:SS % y is the last two digits of the Christian era

dtick: Specify the axis spacing

"M1" every month-> "M2" every two months "D1" every day-> "D2" every two days Others are added every 86400000.0 one day (60 * 60 * 24 = 86400000 seconds per day)

slider

Details in another article Application of graphs using plotly sliders --Qiita

Reference site

official Plotly Python Graphing Library | Python | Plotly

Time axis reference Plotly date axis label display settings: showery's blog

Recommended Posts

plotly trace and layout templates that are likely to be used in scatter plots
I tried to summarize the operations that are likely to be used with numpy-stl
Regular expressions that are easy and solid to learn in Python
Upload and manage packages that are not in conda to anaconda.org
How to smartly define objects that are commonly used in View
Easy program installer and automatic program updater that can be used in any language
Functions that can be used in for statements
A solution to the problem that files containing [and] are not listed in glob.glob ()
Simple statistics that can be used to analyze the effect of measures on EC sites and codes that can be used in jupyter notebook
[New employee studying] Let's summarize the Linux commands that are likely to be used for network construction from now on
Basic algorithms that can be used in competition pros
ANTs image registration that can be used in 5 minutes
[Python] tkinter Code that is likely to be reused
[Python] pandas Code that is likely to be reused
[Django] Field names, user registration, and login methods that can be used in the User model
[Python3] Code that can be used when you want to resize images in folder units
How to set variables that can be used throughout the Django app-useful for templates, etc.-