Styling (2024)

How to style markers in Python with Plotly.


New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Add Marker Border

In order to make markers look more distinct, you can add a border to the markers. This can be achieved by adding the line property to the marker object.

Here is an example of adding a marker border to a faceted scatter plot created using Plotly Express.

In[1]:

import plotly.express as pxdf = px.data.iris()fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")fig.update_traces(marker=dict(size=12, line=dict(width=2, color='DarkSlateGrey')), selector=dict(mode='markers'))fig.show()

Here is an example that creates an empty graph object figure, and then adds two scatter traces with a marker border.

In[2]:

import plotly.graph_objects as go# Generate example dataimport numpy as npnp.random.seed(1)x = np.random.uniform(low=3, high=6, size=(500,))y = np.random.uniform(low=3, high=6, size=(500,))# Build figurefig = go.Figure()# Add scatter trace with medium sized markersfig.add_trace( go.Scatter( mode='markers', x=x, y=y, marker=dict( color='LightSkyBlue', size=20, line=dict( color='MediumPurple', width=2 ) ), showlegend=False ))# Add trace with large markerfig.add_trace( go.Scatter( mode='markers', x=[2], y=[4.5], marker=dict( color='LightSkyBlue', size=120, line=dict( color='MediumPurple', width=12 ) ), showlegend=False ))fig.show()

Fully opaque, the default setting, is useful for non-overlapping markers. When many points overlap it can be hard to observe density.

Control Marker Border with Dash

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python app.py.

Get started with the official Dash docs and learn how to effortlessly style & deploy apps like this with Dash Enterprise.

Sign up for Dash Club → Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture.Join now.

Opacity

Setting opacity outside the marker will set the opacity of the trace. Thus, it will allow greater visibility of additional traces but like fully opaque it is hard to distinguish density.

In[4]:

import plotly.graph_objects as go# Generate example dataimport numpy as npx = np.random.uniform(low=3, high=6, size=(500,))y = np.random.uniform(low=3, high=4.5, size=(500,))x2 = np.random.uniform(low=3, high=6, size=(500,))y2 = np.random.uniform(low=4.5, high=6, size=(500,))# Build figurefig = go.Figure()# Add first scatter trace with medium sized markersfig.add_trace( go.Scatter( mode='markers', x=x, y=y, opacity=0.5, marker=dict( color='LightSkyBlue', size=20, line=dict( color='MediumPurple', width=2 ) ), name='Opacity 0.5' ))# Add second scatter trace with medium sized markers# and opacity 1.0fig.add_trace( go.Scatter( mode='markers', x=x2, y=y2, marker=dict( color='LightSkyBlue', size=20, line=dict( color='MediumPurple', width=2 ) ), name='Opacity 1.0' ))# Add trace with large markersfig.add_trace( go.Scatter( mode='markers', x=[2, 2], y=[4.25, 4.75], opacity=0.5, marker=dict( color='LightSkyBlue', size=80, line=dict( color='MediumPurple', width=8 ) ), showlegend=False ))fig.show()

Marker Opacity

To maximise visibility of density, it is recommended to set the opacity inside the marker marker:{opacity:0.5}. If multiple traces exist with high density, consider using marker opacity in conjunction with trace opacity.

In[5]:

import plotly.graph_objects as go# Generate example dataimport numpy as npx = np.random.uniform(low=3, high=6, size=(500,))y = np.random.uniform(low=3, high=6, size=(500,))# Build figurefig = go.Figure()# Add scatter trace with medium sized markersfig.add_trace( go.Scatter( mode='markers', x=x, y=y, marker=dict( color='LightSkyBlue', size=20, opacity=0.5, line=dict( color='MediumPurple', width=2 ) ), showlegend=False ))# Add trace with large markersfig.add_trace( go.Scatter( mode='markers', x=[2, 2], y=[4.25, 4.75], marker=dict( color='LightSkyBlue', size=80, opacity=0.5, line=dict( color='MediumPurple', width=8 ) ), showlegend=False ))fig.show()

Color Opacity

To maximise visibility of each point, set the color as an rgba string that includes an alpha value of 0.5.

This example sets the marker color to 'rgba(135, 206, 250, 0.5)'. The rgb values of 135, 206, and 250 are from the definition of the LightSkyBlue named CSS color that is is used in the previous examples (See https://www.color-hex.com/color/87cefa). The marker line will remain opaque.

In[6]:

import plotly.graph_objects as go# Generate example dataimport numpy as npx = np.random.uniform(low=3, high=6, size=(500,))y = np.random.uniform(low=3, high=6, size=(500,))# Build figurefig = go.Figure()# Add scatter trace with medium sized markersfig.add_trace( go.Scatter( mode='markers', x=x, y=y, marker=dict( color='rgba(135, 206, 250, 0.5)', size=20, line=dict( color='MediumPurple', width=2 ) ), showlegend=False ))# Add trace with large markersfig.add_trace( go.Scatter( mode='markers', x=[2, 2], y=[4.25, 4.75], marker=dict( color='rgba(135, 206, 250, 0.5)', size=80, line=dict( color='MediumPurple', width=8 ) ), showlegend=False ))fig.show()

Custom Marker Symbols

The marker_symbol attribute allows you to choose from a wide array of symbols to represent markers in your figures.

The basic symbols are: circle, square, diamond, cross, x, triangle, pentagon, hexagram, star, hourglass, bowtie, asterisk, hash, y, and line.

Each basic symbol is also represented by a number. Adding 100 to that number is equivalent to appending the suffix "-open" to a symbol name. Adding 200 is equivalent to appending "-dot" to a symbol name. Adding 300 is equivalent to appending "-open-dot" or "dot-open" to a symbol name.

In the following figure, hover over a symbol to see its name or number. Set the marker_symbol attribute equal to that name or number to change the marker symbol in your figure.

The arrow-wide and arrow marker symbols are new in 5.11

In[7]:

import plotly.graph_objects as gofrom plotly.validators.scatter.marker import SymbolValidatorraw_symbols = SymbolValidator().valuesnamestems = []namevariants = []symbols = []for i in range(0,len(raw_symbols),3): name = raw_symbols[i+2] symbols.append(raw_symbols[i]) namestems.append(name.replace("-open", "").replace("-dot", "")) namevariants.append(name[len(namestems[-1]):])fig = go.Figure(go.Scatter(mode="markers", x=namevariants, y=namestems, marker_symbol=symbols, marker_line_color="midnightblue", marker_color="lightskyblue", marker_line_width=2, marker_size=15, hovertemplate="name: %{y}%{x}<br>number: %{marker.symbol}<extra></extra>"))fig.update_layout(title="Mouse over symbols for name & number!", xaxis_range=[-1,4], yaxis_range=[len(set(namestems)),-1], margin=dict(b=0,r=0), xaxis_side="top", height=1400, width=400)fig.show()

Using a Custom Marker

To use a custom marker, set the symbol on the marker. Here we set it to diamond.

In[8]:

import plotly.express as pxdf = px.data.iris()fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")fig.update_traces( marker=dict(size=8, symbol="diamond", line=dict(width=2, color="DarkSlateGrey")), selector=dict(mode="markers"),)fig.show()

Open Marker Colors

In the previous example, each marker has two colors, a marker color (set in Plotly Express with color="species") and a line color (set on the line with color="DarkSlateGrey". All open markers, like "diamond-open" in the following example, have a transparent fill, which means you can specify only one color. Specify this color using the marker color parameter. This controls the outline color and any dot or cross. For open markers, the line color does nothing.

In[9]:

import plotly.express as pxdf = px.data.iris()fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")fig.update_traces( marker=dict( size=8, symbol="diamond-open", line=dict( width=2, # color="DarkSlateGrey" Line colors don't apply to open markers ) ), selector=dict(mode="markers"),)fig.show()

Setting Marker Angles

New in 5.11

Change the angle of markers by setting angle. Here we set the angle on the arrow markers to 45.

In[10]:

import plotly.express as pxdf = px.data.iris()fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")fig.update_traces( marker=dict( size=12, symbol="arrow", angle=45, line=dict(width=2, color="DarkSlateGrey") ), selector=dict(mode="markers"),)fig.show()

Setting Angle Reference

New in 5.11

In the previous example the angle reference is the default up, whichmeans all makers start at the angle reference point of 0. Set angleref to previous and a marker will take its angle reference from the previous data point.

In[11]:

import pandas as pdimport plotly.express as pximport plotly.graph_objects as godf = px.data.gapminder()fig = go.Figure()for x in df.loc[df.continent.isin(["Europe"])].country.unique()[:5]: fil = df.loc[(df.country.str.contains(x))] fig.add_trace( go.Scatter( x=fil["year"], y=fil["pop"], mode="lines+markers", marker=dict( symbol="arrow", size=15, angleref="previous", ), name=x, ) )fig.show()

Using Standoff to Position a Marker

New in 5.11

When you have multiple markers at one location, you can use standoff on a marker to move it away from the other marker in the direction of the angle. In this example, we set standoff=8 on the arrow marker, which is half the size of the other circle marker, meaning it points exactly at the circle.

In[12]:

import pandas as pdimport plotly.graph_objects as gofrom plotly import datadf = data.gapminder()df = df.loc[(df.continent == "Americas") & (df.year.isin([1987, 2007]))]countries = ( df.loc[(df.continent == "Americas") & (df.year.isin([2007]))] .sort_values(by=["pop"], ascending=True)["country"] .unique())[5:-10]data = {"x": [], "y": [], "colors": [], "years": []}for country in countries: data["x"].extend( [ df.loc[(df.year == 1987) & (df.country == country)]["pop"].values[0], df.loc[(df.year == 2007) & (df.country == country)]["pop"].values[0], None, ] ) data["y"].extend([country, country, None]), data["colors"].extend(["cyan", "darkblue", "white"]), data["years"].extend(["1987", "2007", None])fig = go.Figure( data=[ go.Scatter( x=data["x"], y=data["y"], mode="markers+lines", marker=dict( symbol="arrow", color="royalblue", size=16, angleref="previous", standoff=8, ), ), go.Scatter( x=data["x"], y=data["y"], text=data["years"], mode="markers", marker=dict( color=data["colors"], size=16, ), hovertemplate="""Country: %{y} <br> Population: %{x} <br> Year: %{text} <br><extra></extra>""", ), ])fig.update_layout( title="Population changes 1987 to 2007", width=1000, height=1000, showlegend=False,)fig.show()

Reference

See https://plotly.com/python/reference/ for more information and chart attribute options!

What About Dash?

Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash at https://dash.plot.ly/installation.

Everywhere in this page that you see fig.show(), you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:

import plotly.graph_objects as go # or plotly.express as pxfig = go.Figure() # or any Plotly Express function e.g. px.bar(...)# fig.add_trace( ... )# fig.update_layout( ... )from dash import Dash, dcc, htmlapp = Dash()app.layout = html.Div([ dcc.Graph(figure=fig)])app.run_server(debug=True, use_reloader=False) # Turn off reloader if inside Jupyter
Styling (2)
Styling (2024)

FAQs

What is the meaning of the word "styling"? ›

Britannica Dictionary definition of STYLING. [noncount] : the way in which something is designed. a car with sleek new styling. clothing with classic styling.

What does you styling mean? ›

The styling of an object is the design and appearance of it. The car neatly blends classic styling into a smooth modern package. 2. uncountable noun [oft N n] The styling of someone's hair is the way in which it is cut and arranged.

What is styling on someone? ›

also : to select and arrange the clothing, hair, makeup, etc. of (someone) to create a particular fashion look.

What is the difference between style and styling? ›

Style is like your persona and how you dress kinda like an aesthetic. Styling is picking an article of clothing and finding things that match its vibe mostly meaning color and style.

How do you use styling in a sentence? ›

The styling for the shoot highlighted the athlete's style. Here are the best shampoos for every type of curl and styling need.

What does in style mean slang? ›

1. : popular or fashionable. 2. : in a way that is impressive or admired because it shows talent, good taste, etc. : in a stylish way.

What is a fancy word for style? ›

Some common synonyms of style are craze, fad, fashion, mode, rage, and vogue. While all these words mean "the usage accepted by those who want to be up-to-date," style often implies a distinctive fashion adopted by people of taste. a media baron used to traveling in style.

What is the significance of styling? ›

Your style can boost your confidence and the way you feel about yourself. It can also make you feel powerful and independent. You can create your signature style statement with how you clothe yourself.

What does it mean when someone is styling you? ›

First, styling is done for someone – in short it is creating a bundle of items that go together as an outfit to help a potential buyer have a certain look or style.

What does styling it out mean? ›

to behave confidently in an embarrassing situation so that people do not notice it: I fell over during my last song but I managed to style it out to look like a dance move. There was me styling it out, pretending that I knew what they were talking about. Confidence & self-assurance.

What is style in a person? ›

A style personality is how the traits of your personality and character are communicated through clothing. No one style personality is better than another. Each is unique and positive in its own way.

What is a catchy word for style? ›

chichi, comfort, craze, dash, delicacy, ease, fad, grandeur, luxury, panache, polish, rage, refinement, savoir-faire, smartness, stylishness, urbanity, vogue.

What is a stylish person called? ›

synonyms: fashionable chic, smart, tony, voguish. elegant and stylish. chichi. affectedly trendy and fashionable. classy, posh, swish.

What is the slang word for style? ›

Swag — a stylish and confident appearance. Drip — an individual's fashionable and trendy outfit or overall style. Flex — to show off or display one's fashionable clothing or accessories in a proud and confident manner. Fresh — new, stylish, or impressive. Fit = outfit — fashionable clothing.

What is the difference between styling and designing? ›

Fashion Stylist and Fashion Designer

A fashion designer is someone who creates new clothing and accessory designs, while a fashion stylist is responsible for curating and organising clothing and accessories to create a cohesive, visually appealing look for a particular project or client.

What is the best definition of style? ›

the manner in which something is expressed or performed, considered as separate from its intrinsic content, meaning, etc. a distinctive, formal, or characteristic manner of expression in words, music, painting, etc. elegance or refinement of manners, dress, etc.

What is styling process? ›

Styling Process

Combine new items together with existing pieces from closet. • Style outfits for client's lifestyle (i.e.; career, casual, social, etc.) incorporating accessories to define style.

Top Articles
Latest Posts
Article information

Author: Dean Jakubowski Ret

Last Updated:

Views: 5560

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Dean Jakubowski Ret

Birthday: 1996-05-10

Address: Apt. 425 4346 Santiago Islands, Shariside, AK 38830-1874

Phone: +96313309894162

Job: Legacy Sales Designer

Hobby: Baseball, Wood carving, Candle making, Jigsaw puzzles, Lacemaking, Parkour, Drawing

Introduction: My name is Dean Jakubowski Ret, I am a enthusiastic, friendly, homely, handsome, zealous, brainy, elegant person who loves writing and wants to share my knowledge and understanding with you.