Sunday, September 22, 2019

Define custom color for plots

In the post Using Matplotlib Built-in Styles to customize plots we customized our plots for background colors, gridlines, line widths, fonts, font size etc. In this post we'll see how to change the color of the points on the plot.

Defining Custom Colors

To change the color of the points, pass c to scatter() with the name of a color to use in quotation marks as shown in the code below:

ax.scatter(x_values, y_values, c='blue', s=10)

We can also define custom colors using the RGB color model. To define a color, pass the c argument a tuple with three decimal values (one each for red, green, and blue in that order), using values between 0 and 1. Values closer to 0 produce dark colors, and values closer to 1 produce lighter colors. For example, the following line creates a plot with light-green dots:

ax.scatter(x_values, y_values, c=(0, 0.8, 0), s=10) 

If we use this approach we get the following warning - 'c' argument looks like a single numeric RGB or RGBA sequence, which should be a voided as value-mapping will have precedence in case its length matches with 'x'  & 'y'.  Please use a 2-D array with a single row if you really want to specify
the same RGB or RGBA value for all points.


Let's see the implementation in the following program:

import matplotlib.pyplot as plt

x_values = range(1,101)
y_values = [x**3 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, c='blue', s=10)

# Setting chart title and label axes
ax.set_title("Cube Numbers", fontsize=24)
ax.set_xlabel("Value", fontsize=14)
ax.set_ylabel("Cube of Value", fontsize=14)

# Set size of tick labels.
ax.tick_params(axis='both', labelsize=14)

# Set the range for each axis.
ax.axis([0, 110, 0, 110000])
plt.show()


The output of the program is shown below:




The next define custom colors using the RGB color mode:

import matplotlib.pyplot as plt

x_values = range(1,101)
y_values = [x**3 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, c=(0,0.8,0), s=10)

# Setting chart title and label axes
ax.set_title("Cube Numbers", fontsize=24)
ax.set_xlabel("Value", fontsize=14)
ax.set_ylabel("Cube of Value", fontsize=14)

# Set size of tick labels.
ax.tick_params(axis='both', labelsize=14)

# Set the range for each axis.
ax.axis([0, 110, 0, 110000])
plt.show()


The output of the program is shown below:


Using a Colormap

A colormap is a series of colors in a gradient that moves from a starting to an ending color. We use colormaps in visualizations to emphasize a pattern in the data. For example, we might make low values a light color and high values a darker color.

The pyplot module includes a set of built-in colormaps. To use one of these colormaps, we need to specify how pyplot should assign a color to each point in the data set. The following code assign each point a color based on its y-value:

ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Reds, s=10)

Let's see how to use this in the program:

import matplotlib.pyplot as plt

x_values = range(1,101)
y_values = [x**3 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, c='blue', s=10)
ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10)
# Setting chart title and label axes
ax.set_title("Cube Numbers", fontsize=24)
ax.set_xlabel("Value", fontsize=14)
ax.set_ylabel("Cube of Value", fontsize=14)

# Set size of tick labels.
ax.tick_params(axis='both', labelsize=14)

# Set the range for each axis.
ax.axis([0, 110, 0, 110000])
plt.show()

We pass the list of y-values to c, and then tell pyplot which colormap to use using the cmap argument. This code colors the points with lower y-values light blue and colors the points with higher y-values dark blue. The output of the program is shown below:


Saving Plots Automatically

If we want our program to automatically save the plot to a file, we can replace the call to plt.show() with a call to plt.savefig():

plt.savefig('cubes_plot.png', bbox_inches='tight')

The first argument is a filename for the plot image, which will be saved in the same directory as scatter_squares.py. The second argument trims extra whitespace from the plot. If you want the extra whitespace around the plot, just omit this argument. See the following program:

import matplotlib.pyplot as plt

x_values = range(1,101)
y_values = [x**3 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, c='blue', s=10)
#ax.scatter(x_values, y_values, c=(0,0.8,0), s=10)
ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10)
# Setting chart title and label axes
ax.set_title("Cube Numbers", fontsize=24)
ax.set_xlabel("Value", fontsize=14)
ax.set_ylabel("Cube of Value", fontsize=14)

# Set size of tick labels.
ax.tick_params(axis='both', labelsize=14)

# Set the range for each axis.
ax.axis([0, 110, 0, 110000])
plt.savefig('cubes_plot.png', bbox_inches='tight')


Run the program and check your project directory, you should see the file cubes_plot.png

Here I am ending today's post. In the next post we'll use Python to generate data for a random walk, and then use Matplotlib to create a visually appealing representation of that data. So till we meet next keep practicing and learning Python as Python is easy to learn!

Share:

0 comments:

Post a Comment