×

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might be challenging.

Choosing a decent colour scheme is a science in and of itself, and there are several excellent materials available on the subject (listed at the end of this post). This tutorial is all about what to do after you've decided on your colour scheme.

This package's great support for colour and plot management comes at the cost of a little of complexity when figuring out how to mix the various classes and methods.

Let's begin with a few simple plots. We can use matplotlib's imshow function to plot the density of a numpy array on a graph:

SYNTAX

import matplotlib.pytplot as plt

# define geographic extent of the image in latitude/longitude

bounds = [10.0, 11.0, 57.0, 58.0]

im = plt.imshow(np.log(data+1),

                origin='lower',

                extent=bounds)

plt.colorbar(im)

Take note of the fact that we have shown the density logarithm. There's more to it than that, though. In the same way, the data from the United States Census Bureau may be used to create a line graph.

for year in sorted(data.year.unique(), reverse=True):

    year_data = data.loc[data.year==year,:]

    plt.plot(year_data['month'],

             year_data['imports'],

             lw=2,

             label=year)

added some axis labels and a legend, and the finished product will resemble this:

OUTPUT

Colors In Python

Even though the default plots appear to be rather excellent, there are a few flaws that need to be addressed. To view all of the data in the density plot, I had to plot the logarithm of the density. The legend's colour bar, on the other hand, shows the density's logarithm as well, and that's not what we want to see. Furthermore, the plot's predominant hue ended up being black and white.

Because colours are reused on the line plots, it's a little difficult to tell which line belongs to which year. Additionally, the line plot's colour scheme differs from the density plot's colour scheme, making the two plots appear disjointed.

Adjusting existing color maps

Let's begin with a look at the density plot. Each latitude/longitude coordinate has a single value for ocean traffic density. There are two phases involved in transforming that number into a colour: first, find the number.

To get a number between 0 and 1, we use a normalizer to transform the density value.

To represent red, green, and blue with three integers, we utilise the colour map (i.e., an RGB value).

There are numerous classes in Matplotlib that can do this. Matplotlib's normalizers, both linear and nonlinear, help us normalise our densities. Nonlinear scaling is possible by using classes such as PowerNorm or LogNorm rather than the Normalize class, for example.

Color maps will be discussed more in the following part, so for the time being we'll utilise one that we got from the library by calling the method get cmap.

SYNTAX

from matplotlib.cm import get_cmap

from matplotlib.colors import PowerNorm

cmap = get_cmap('inferno')

# we can adjust how our values are normalized

norm = PowerNorm(0.4, vmin=0, vmax=100)

# the colormap and normalizer can be passed directly to imshow

im = ax.imshow(data,

               cmap=cmap,

               norm=norm,

               origin='lower',

               extent=bounds)

# create a color bar with 10 ticks

plt.colorbar(im,ticks=np.arange(0, norm.vmax, norm.vmax/10))

You'll see that the colour bars have been updated to reflect the new values. Let's use the same colour scheme for our line graph. We'll normalise linearly this time, but we'll need to manually produce our colours:

SYNTAX

line_norm = Normalize(1980, 2010)

for year in sorted(data.year.unique(), reverse=True):

    year_data = data.loc[data.year==year, :]

    norm_value = line_norm(year)

    col = cmap(norm_value)

    ax.plot(year_data['month'],

            year_data['imports'],

            lw=2,

            c=col,

            label=year)

# set the background and grid colors

plt.gca().set_facecolor('#111111')

plt.grid(color='#555555')

Viewing the density plot and line plot side-by-side, we get this:

OUTPUT

Colors In Python

That's a step in the right direction, then. At the very least, both plots now appear to have been created by the same individual. Although these stories still have a lot to quarrel over, at least we now know how to handle it.

Customized Color Schemes

Choosing a colour scheme has several benefits. Clarity is critical, and there has been a lot written on how to utilise colour to improve the readability of plots. matplotlib's built-in colormaps make this task a lot easier. A person's personal sense of style is critical as well. Or perhaps you wish to adhere to the corporate style guidelines and feel that 'inferno' does not adequately convey the information you are delivering. To achieve this, we must first create our own colour scheme.


Related Topics

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

Event Key in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.

XXhash Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

6 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Python Subprocess Call Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Iterate through the list in Python

One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order...

7 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Image to NumPy Arrays in Python

Image is a simple process of working model confined to machine learning, Python works with the image in the data format of width and height i.e. Images are excelled into...

3 minutes read.