Discrete (2024)

How to use and configure discrete color sequences, also known as categorical or qualitative color scales.


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.

Discrete vs Continuous Color

In the same way as the X or Y position of a mark in cartesian coordinates can be used to represent continuous values (i.e. amounts or moments in time) or categories (i.e. labels), color can be used to represent continuous or discrete data. This page is about using color to represent categorical data using discrete colors, but Plotly can also represent continuous values with color.

Discrete Color Concepts

This document explains the following discrete-color-related concepts:

  • color sequences are lists of colors to be mapped onto discrete data values. No interpolation occurs when using color sequences, unlike with continuous color scales, and each color is used as-is. Color sequence defaults depend on the layout.colorway attribute of the active template, and can be explicitly specified using the color_discrete_sequence argument for many Plotly Express functions.
  • legends are visible representations of the mapping between colors and data values. Legend markers also change shape when used with various kinds of traces, such as symbols or lines for scatter-like traces. Legends are configurable under the layout.legend attribute. Legends are the discrete equivalent of continuous color bars

Discrete Color with Plotly Express

Most Plotly Express functions accept a color argument which automatically assigns data values to discrete colors if the data is non-numeric. If the data is numeric, the color will automatically be considered continuous. This means that numeric strings must be parsed to be used for continuous color, and conversely, numbers used as category codes must be converted to strings.

For example, in the tips dataset, the smoker column contains strings:

In[1]:

import plotly.express as pxdf = px.data.tips()fig = px.scatter(df, x="total_bill", y="tip", color="smoker", title="String 'smoker' values mean discrete colors")fig.show()

The size column, however, contains numbers:

In[2]:

import plotly.express as pxdf = px.data.tips()fig = px.scatter(df, x="total_bill", y="tip", color="size", title="Numeric 'size' values mean continuous color")fig.show()

Converting this column to strings is very straightforward, but note that the ordering in the legend is not sequential by default (see below for how to control discrete order):

In[3]:

import plotly.express as pxdf = px.data.tips()df["size"] = df["size"].astype(str)fig = px.scatter(df, x="total_bill", y="tip", color="size", title="String 'size' values mean discrete colors")fig.show()

In[4]:

import plotly.express as pxdf = px.data.tips()df["size"] = df["size"].astype(str) #convert to stringdf["size"] = df["size"].astype(float) #convert back to numericfig = px.scatter(df, x="total_bill", y="tip", color="size", title="Numeric 'size' values mean continuous color")fig.show()

Discrete Colors in 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.

Out[5]:

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.

Color Sequences in Plotly Express

By default, Plotly Express will use the color sequence from the active template's layout.colorway attribute, and the default active template is plotly which uses the plotly color sequence. You can choose any of the following built-in qualitative color sequences from the px.colors.qualitative module, however, or define your own.

In[6]:

import plotly.express as pxfig = px.colors.qualitative.swatches()fig.show()

Color sequences in the px.colors.qualitative module are stored as lists of CSS colors:

In[7]:

import plotly.express as pxprint(px.colors.qualitative.Plotly)
['#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3', '#FF6692', '#B6E880', '#FF97FF', '#FECB52']

Here is an example that creates a scatter plot using Plotly Express, with points colored using the built-in qualitative G10 color sequence.

In[8]:

import plotly.express as pxdf = px.data.gapminder()fig = px.line(df, y="lifeExp", x="year", color="continent", line_group="country", line_shape="spline", render_mode="svg", color_discrete_sequence=px.colors.qualitative.G10, title="Built-in G10 color sequence")fig.show()
See Also
Discrete

Explicitly Constructing a Color Sequence

The Plotly Express color_discrete_sequence argument accepts explicitly-constructed color sequences as well, as lists of CSS colors:

In[9]:

import plotly.express as pxdf = px.data.gapminder().query("year == 2007")fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country", color_discrete_sequence=["red", "green", "blue", "goldenrod", "magenta"], title="Explicit color sequence" )fig.show()

Warning: If your color sequence is has fewer colors than the number of unique values in the column you are mapping to color, the colors will cycle through and repeat, possibly leading to ambiguity:

In[10]:

import plotly.express as pxdf = px.data.tips()fig = px.scatter(df, x="total_bill", y="tip", color="day", color_discrete_sequence=["red", "blue"], title="<b>Ambiguous!</b> Explicit color sequence cycling because it is too short" )fig.show()

Directly Mapping Colors to Data Values

The example above assigned colors to data values on a first-come-first-served basis, but you can directly map colors to data values if this is important to your application with color_discrete_map. Note that this does not change the order in which values appear in the figure or legend, as can be controlled below:

In[11]:

import plotly.express as pxdf = px.data.gapminder().query("year == 2007")fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country", color_discrete_map={ "Europe": "red", "Asia": "green", "Americas": "blue", "Oceania": "goldenrod", "Africa": "magenta"}, title="Explicit color mapping")fig.show()

If your data set already contains valid CSS colors which you wish to use directly, you can pass the special value "identity" to color_discrete_map, in which case the legend is hidden by default, and the color does not appear in the hover label:

In[12]:

import plotly.express as pxfig = px.bar(x=["a","b","c"], y=[1,3,2], color=["red", "goldenrod", "#00D"], color_discrete_map="identity")fig.show()

Controlling Discrete Color Order

Plotly Express lets you specify an ordering over categorical variables with category_orders, which will apply to colors and legends as well as symbols, axes and facets. This can be used with either color_discrete_sequence or color_discrete_map.

In[13]:

import plotly.express as pxdf = px.data.gapminder().query("year == 2007")fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country", color_discrete_sequence=["red", "green", "blue", "goldenrod", "magenta"], category_orders={"continent": ["Oceania", "Europe", "Asia", "Africa", "Americas"]}, title="Explicit color sequence with explicit ordering" )fig.show()

In[14]:

import plotly.express as pxdf = px.data.gapminder().query("year == 2007")fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country", color_discrete_map={ "Europe": "red", "Asia": "green", "Americas": "blue", "Oceania": "goldenrod", "Africa": "magenta"}, category_orders={"continent": ["Oceania", "Europe", "Asia", "Africa", "Americas"]}, title="Explicit color mapping with explicit ordering" )fig.show()

Using Sequential Scales as Discrete Sequences

In most cases, discrete/qualitative/categorical data values have no meaningful natural ordering, such as in the continents example used above. In some cases, however, there is a meaningful order, and in this case it can be helpful and appealing to use part of a continuous scale as a discrete sequence, as in the following wind rose chart:

In[15]:

import plotly.express as pxdf = px.data.wind()fig = px.bar_polar(df, r="frequency", theta="direction", color="strength", color_discrete_sequence= px.colors.sequential.Plasma_r, title="Part of a continuous color scale used as a discrete sequence" )fig.show()

This works because just like in px.colors.qualitative, all built-in continuous color scales are stored as lists of CSS colors:

In[16]:

import plotly.express as pxprint(px.colors.sequential.Plasma)
['#0d0887', '#46039f', '#7201a8', '#9c179e', '#bd3786', '#d8576b', '#ed7953', '#fb9f3a', '#fdca26', '#f0f921']

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
Discrete (2)
Discrete (2024)

FAQs

What is a discrete solution? ›

With the aid of algebraic methods the discrete solution of a problem is obtained from the discrete problem. At this layer the solution consists of a vector of numbers which has to fulfill the requirements of the given algebraic equation system.

Why is it called discrete? ›

Discrete objects are those which are separated from (not connected to/distinct from) each other.

What is an example of a discrete data in math? ›

Discrete data is distinct, individual, unique numbers, like counting. The attendance at a soccer game is an example of discrete data. The number of people can be individually counted (1, 2, 3, . . .) and can not be divided into smaller parts. There is no 0.5 person.

What is the purpose of discrete? ›

Discrete Mathematics is the backbone of Computer Science

Concepts and notations from discrete mathematics are useful in studying and describing objects and problems in all branches of computer science, such as computer algorithms, programming languages, cryptography, automated theorem proving, and software development.

What is a discrete answer? ›

Another way to think about discrete data is to think of it as data in which only certain values are possible. This means that discrete data only involves answering yes or no questions, such as "Does a product work?" The only possible answer is "yes" or "no," and these are discrete answers.

What does a discrete sample mean? ›

A sample space is called discrete if it is a finite or a countably infinite set. It is called continuous or a continuum otherwise.

What is discrete in simple words? ›

Discrete means separate or divided. A discrete unit is a separate part of something larger. A room is a discrete space within a house, just as the crankshaft is a discrete part of a car engine. If something is discrete, it has its own space. An ice cube comes from an ice tray, but it has its own discrete compartment.

Does discrete mean hidden? ›

Discreet means on the down low, under the radar, careful; but discrete means "individual" or "detached." They come from the same ultimate source, the Latin discrētus, for "separated or distinct," but discreet has taken its own advice and quietly gone its separate way.

What makes it discrete? ›

Discrete data is a count that involves integers — only a limited number of values is possible. This type of data cannot be subdivided into different parts. Discrete data includes discrete variables that are finite, numeric, countable, and non-negative integers.

Is age discrete or continuous? ›

If you know a person's time of birth, you could measure their age precisely up to the second or even millisecond if you wanted to. In this sense, age is a continuous variable. However, we don't usually care about a person's exact age. Instead, we treat age as a discrete variable and count age in years.

What are discrete questions? ›

Discrete choice questions are typically straightforward – “Which product do you prefer?” However, in some situations, the respondent may be thinking, “It depends.” This article describes these situations and some possible solutions. Identifying Issues in Discrete Choice Questions.

Is money discrete or continuous? ›

More Examples of Discrete Data

No matter if bottles, glasses, tables, or cars. They can only take integer values. Money can be considered both, but physical money like banknotes and coins are definitely discrete.

Is discrete math hard? ›

Discrete mathematics has a well-deserved reputation as one of the more challenging 200-level mathematics courses, so be prepared to work hard! Part of the reason discrete mathematics is difficult is that it has a significantly different flavor than the mathematics classes you have taken prior to this course.

What is discrete math used for in real life? ›

Discrete mathematics provides foundational concepts and tools for solving problems in computer science, cryptography, information theory, and various areas of engineering and science. The skill of standing out online is needed more than ever in today's digital world.

Is discrete math taught in high school? ›

It is the mathematics that underlies most of high-school algebra and calculus. Continuous mathematics deals with the uncountable set, such as the re- als, whereas discrete mathematics deals with countable, or finite sets of numbers, such as the integers or rationals.

What is discrete vs non-discrete? ›

Discrete Parts

Any part with an individual traceability requirement (anything with a serial number). Any other part can be defined as Non-Discrete.

What does discrete mean in chemistry? ›

Discrete just means that there is a finite number as opposed to a continuous amount. In regards to chemistry, we describe energy as being transferred in discrete units or packets.

What is an example of a discrete function? ›

The number of students in a classroom: This is another example of a discrete function since there are no fractional parts of a student. Even if the classroom is identified by numbers, these room numbers are commonly whole numbers and do not have fractional or decimal parts of a room number.

How to know if it is discrete or continuous? ›

The key differences are: Discrete data is the type of data that has clear spaces between values. Continuous data is data that falls in a constant sequence. Discrete data is countable while continuous — measurable.

Top Articles
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 6432

Rating: 4.2 / 5 (73 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.