Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

preface

All drawings provided by Matplotlib come with default styles. While this allows for quick drawing, sometimes you may need to customize the color and style of your drawing to produce a more elegant, aesthetically pleasing image. Matplotlib is designed with this requirement in mind, making it easy to adjust the colors and styles of matplotlib graphics.

Custom colors

In our lives, we probably have our own preferences for color combinations and aesthetics, so we might want Matplotlib to follow a custom color scheme so that the graphics we draw fit better on a document or web page. There are several ways to define a color in Matplotlib. Common methods include:

  1. Triplets: colors can be described as a real triplet, namely red, blue, and green components of colors, each of which is within the range [0,1]. Thus, (1.0, 0.0, 0.0) represents pure red, while (1.0, 0.0, 1.0) represents pink.

  2. Quadruplets: The first three elements are the same as triplet definitions, and the fourth element defines the transparency value. This value is also in the range [0,1]. When rendering graphics into image files, using transparent colors allows the graphics to blend with the background.

  3. Predefined names: Matplotlib interprets standard HTML color names as actual colors. For example, the string red can be represented as red. Also, some of the colors have concise aliases, as shown in the following table:

    The alias color
    b blue
    g green
    r red
    c cyan
    m magenta
    y yellow
    k black
    w white
  4. HTML Color Strings: Matplotlib can interpret HTML color strings as actual colors. These strings are defined as #RRGGBB, where RR, GG, and BB are the hexadecimal encoded red, green, and blue components.

  5. Grayscale String: Matplotlib interprets the string representation of floating-point values as grayscale, such as 0.75 for medium-light gray.

Draw graphs using custom colors

The color of the curve can be set by setting the color(or equivalent shorthand c) of the plt.plot() function, as follows:

import numpy as np
import matplotlib.pyplot as plt
def pdf(x, mu, sigma) :
    a = 1. / (sigma * np.sqrt(2. * np.pi))
    b = -1. / (2. * sigma ** 2)
    return a * np.exp(b * (x - mu) ** 2)
x = np.linspace(-6.6.1000)
for i in range(5):
    samples = np.random.standard_normal(50)
    mu, sigma = np.mean(samples), np.std(samples)
    plt.plot(x, pdf(x, mu, sigma), color = str(15.*(i+1)))
plt.plot(x, pdf(x, 0..1.), color = 'k')
plt.plot(x, pdf(x, 0.2.1.), color = '#00ff00')
plt.plot(x, pdf(x, 0.4.1.), color = (0.9.0.9.0.0))
plt.plot(x, pdf(x, 0.4.1.), color = (0.9.0.9.0.0.0.8))
plt.show()
Copy the code

Draw a scatter plot using custom colors

You can control the color of a scatter plot in the same way you control a graph. There are two forms available:

  1. Use the same color for all points: All points will be displayed in the same color.
  2. Define a different color for each point: Provide a different color for each point.

Use the same color for all points

Using two sets of points y_1 and y_2 extracted from the bivariate Gaussian distribution, the midpoints in each set have the same color:

import numpy as np
import matplotlib.pyplot as plt
y_1 = np.random.standard_normal((150.2))
y_1 += np.array((-1, -1)) # Center the distrib. at <-1, -1>
y_2 = np.random.standard_normal((150.2))
y_2 += np.array((1.1)) # Center the distrib. at <1, 1>
plt.scatter(y_1[:,0], y_1[:,1], color = 'c')
plt.scatter(y_2[:,0], y_2[:,1], color = 'b')
plt.show()
Copy the code

Define a different color for each point

There are always drawing scenarios where you need to draw different colors for different categories of points to see how different categories differ. Taking Fisher’s IRIS dataset as an example, the data in the dataset are similar to the following:

5.0, 3.3, 1.4, 0.2, Iris - setosa 7.0, 3.2, 4.7, 1.4, Iris - versicoloCopy the code

Each point of the dataset is stored in a comma-separated list. The last column gives the label for each point (there are three types of tags: Iris-virginica, Iris-versicolor, and Iris-vertosa). In the example, the color of the dots will depend on their label, as follows:

import numpy as np
import matplotlib.pyplot as plt
label_set = (
    b'Iris-setosa'.b'Iris-versicolor'.b'Iris-virginica'.)def read_label(label) :
    return label_set.index(label)
data = np.loadtxt('iris.data', delimiter = ', ', converters = { 4 : read_label })
color_set = ('c'.'y'.'m')
color_list = [color_set[int(label)] for label in data[:,4]]
plt.scatter(data[:,0], data[:,1], color = color_list)
plt.show()
Copy the code

Tips: Specify a unique color for each of the three possible labels. Colors are defined in color_set and labels are defined in label_set. The i-th label in label_set is associated with the i-th color in color_set. We then use them to convert the label list to the color list color_list. Then call plt.Scatter () once to show all the points and their colors. We could also do this by calling plt.scatter() separately for three different categories, but this would require more code. Another thing to note is that if two points may have the same coordinates but have different labels, the color displayed will be the color of the point after drawing. A transparent color can be used to show the overlapping points.

Use custom colors for edges of data points in a scatter plot

Like the color parameter to control the color of the points, you can use the Edgecolor parameter to control the color of the edges of the data points. You can set the edges of each point to the same color:

import numpy as np
import matplotlib.pyplot as plt
data = np.random.standard_normal((100.2))
plt.scatter(data[:,0], data[:,1], color = '1.0', edgecolor='r')
plt.show()
Copy the code

Tips: You can also set the color of the edges of each dot as described in the Define a Different color for each dot section

Draw bar charts using custom colors

Control the color used to draw bar charts works in the same way as for graphs and scatter plots, namely with the optional color parameter:

import numpy as np
import matplotlib.pyplot as plt
w_pop = np.array([5..30..45..22.])
m_pop = np.array( [5..25..50..20.])
x = np.arange(4)
plt.barh(x, w_pop, color='m')
plt.barh(x, -m_pop, color='c')
plt.show()
Copy the code

Using the Pyplot.bar () and Pyplot.barh () functions to customize colors to draw bar graphs works exactly the same as pyplot.Scatter (), just setting the optional color parameter and edgecolor to control the color of the bar edges.

import numpy as np
import matplotlib.pyplot as plt
values = np.random.random_integers(99, size = 50)
color_set = ('c'.'m'.'y'.'b')
color_list = [color_set[(len(color_set) * val) // 100] for val in values]
plt.bar(np.arange(len(values)), values, color = color_list)
plt.show()
Copy the code

Draws pie charts using custom colors

The method for customizing pie chart colors is similar to the bar chart:

import numpy as np
import matplotlib.pyplot as plt
color_set = ('c'.'m'.'y'.'b')
values = np.random.rand(6)
plt.pie(values, colors = color_set)
plt.show()
Copy the code

The pie chart accepts a list of colors using the colors parameter (note that colors here, not the color used in plt.plot()). However, if the number of colors is less than the number of elements in the list of input values, plt.pie() loops through the colors in the list of colors. In the example, a list of four colors is used to color the pie chart with six values, so two of the colors will be used twice.

Draw a box diagram using custom colors

Modify the line color in the box diagram:

import numpy as np
import matplotlib.pyplot as plt
values = np.random.randn(100)
b = plt.boxplot(values)
for name, line_list in b.items():
    for line in line_list:
        line.set_color('m')
plt.show()
Copy the code

Draw a scatter plot using a color map

If you want to use multiple colors in a graph, defining each color individually is not the best solution, and color mapping can solve this problem. A color map defines a color as a continuous function of a variable corresponding to a value (color). Matplotlib provides several common color mappings; Most are continuous color gradients. Color maps are defined in the matplotib.cm module, which provides functions to create and use color maps. It also provides predefined color map choices. The pyplot.scatter() function takes a list of values for the color parameter, which are interpreted as an index of the color map when the cmap parameter is provided:

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
n = 256
angle = np.linspace(0.8 * 2 * np.pi, n)
radius = np.linspace(. 5.1., n)
x = radius * np.cos(angle)
y = radius * np.sin(angle)
plt.scatter(x, y, c = angle, cmap = cm.hsv)
plt.show()
Copy the code

Tips: A number of predefined color mappings are provided in the matplotlib.cm module, where Cm. HSV contains the full spectrum of colors.

Draw bar charts using color maps

The plt.Scatter () function has built-in support for color mapping, as do some other drawing functions. However, some functions (such as Pyplot.bar ()) do not have built-in support for color mapping. But Matplotlib can explicitly generate colors from color maps:

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.colors as col
values = np.random.random_integers(99, size = 50)
cmap = cm.ScalarMappable(col.Normalize(0.99), cm.binary)
plt.bar(np.arange(len(values)), values, color = cmap.to_rgba(values))
plt.show()
Copy the code

Tips: First create a color map cmap to map values in the range [0, 99] to the color of matplotlib.cm.binary. The function map.to_rgba then converts the list of values to a list of colors. Therefore, although plt.bar does not have built-in support for color mapping, it is still possible to implement color mapping using uncomplicated code.

Create custom color schemes

The default colors used by Matplotlib are primarily intended for printed documents or publications. So, by default, the background is white, and labels, axes, and other comments are black, which color scheme we may need to use in some different usage environments; For example, set the graphics background to black and comments to white. In Matplotlib, various objects, such as axes, graphs, and labels, can be modified individually. But changing the color configuration of these objects one by one is not optimal. In Matplotlib, all objects can change their default colors using centralized configuration:

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
mpl.rc('lines', linewidth = 2.)
mpl.rc('axes', facecolor = 'k', edgecolor = 'w')
mpl.rc('xtick', color = 'w')
mpl.rc('ytick', color = 'w')
mpl.rc('text', color = 'w')
mpl.rc('figure', facecolor = 'k', edgecolor ='w')
mpl.rc('axes', prop_cycle = mpl.cycler(color=[(0.1.. 5.75.), (0.5.. 5.75.)]))
x = np.linspace(0.7.1024)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
plt.show()
Copy the code

Series of links

Drawing common Matplotlib statistics – Digging gold (juejin. Cn)