Matplotlib 简明教程
Matplotlib - Colors
Matplotlib 为管理绘图中的颜色提供了多种选项,允许用户增强视觉吸引力并有效地传达信息。
Matplotlib provides several options for managing colors in plots, allowing users to enhance the visual appeal and convey information effectively.
可以为绘图中的不同元素设置颜色,例如线、标记和填充区域。例如,在绘图数据时,可使用颜色参数指定线条颜色。同样,散点图允许为各个点设置颜色。下图说明了绘图中不同元素的颜色 −
Colors can be set for different elements in a plot, such as lines, markers, and fill areas. For instance, when plotting data, the color parameter can be used to specify the line color. Similarly, scatter plots allow setting colors for individual points. The image below illustrates the colors for the different elements in a plot −
Color Representation Formats in Matplotlib
Matplotlib 支持各种表示颜色的格式,包括 −
Matplotlib supports various formats for representing colors, which include −
-
RGB or RGBA Tuple
-
Hex RGB or RGBA String
-
Gray Level String
-
"Cn" Color Spec
-
Named colors
下面对每种格式进行了简要讨论,并提供了相应的示例。
Below are the brief discussions about each format with an appropriate example.
The RGB or RGBA Tuple format
您可以使用范围在 [0, 1] 之内的浮点值元组来表示红色、绿色、蓝色和 Alpha(透明度)值。例如: (0.1, 0.2, 0.5) 或 (0.1, 0.2, 0.5, 0.3)。
You can use the tuple of float values in the range between [0, 1] to represent Red, Green, Blue, and Alpha (transparency) values. like: (0.1, 0.2, 0.5) or (0.1, 0.2, 0.5, 0.3).
Example
以下示例演示如何使用 RGB 或 RGBA 元组指定绘图的 face color 。
The following example demonstrates how to specify the face color of a plot using the RGB or RGBA tuple.
import matplotlib.pyplot as plt
import numpy as np
# sample data
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
# RGB tuple for specifying facecolor
fig, ax = plt.subplots(figsize=(7,4), facecolor=(.18, .31, .31))
# Plotting the data
plt.plot(t, s)
# Show the plot
plt.show()
print('successfully used the RGB tuple for specifying colors..')
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
successfully used the RGB tuple for specifying colors..
The Hex RGB or RGBA String format
一个表示不区分大小写的 hex RGB 或 RGBA 的字符串,例如:'#0F0F0F' 或 '#0F0F0F0F' 可用于指定 matplotlib 中的颜色。
A string representing the case-insensitive hex RGB or RGBA, like: '#0F0F0F' or '#0F0F0F0F' can be used to specify a color in matplotlib.
Example
此示例使用 hex 字符串指定 axis face color 。
This example uses the hex string to specify the axis face color.
import matplotlib.pyplot as plt
import numpy as np
# Example data
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
# Hex string for specifying axis facecolor
fig, ax = plt.subplots(figsize=(7,4))
ax.set_facecolor('#eafff5')
# Plotting the data
plt.plot(t, s)
# Show the plot
plt.show()
print('successfully used the Hex string for specifying colors..')
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
successfully used the Hex string for specifying colors..
此外,一个 shorthand hex RGB or RGBA string (不区分大小写)可用于指定 matplotlib 中的颜色。这等效于重复字符的 hex 简写。例如:'#abc'(等效于 '#aabbcc')或 '#abcd'(等效于 '#aabbccdd')。
Also, a shorthand hex RGB or RGBA string(case-insensitive) can be used to specify colors in matplotlib. Which are equivalent to the hex shorthand of duplicated characters. like: '#abc' (equivalent to '#aabbcc') or '#abcd' (equivalent to '#aabbccdd').
The Gray Level String format
我们可以使用 [0, 1] 范围内的浮点值字符串表示来表示灰度级。例如,“0”表示黑色,“1”表示白色,“0.8”表示浅灰色。
We can use a string representation of a float value in the range of [0, 1] inclusive for the gray level. For example, '0' represents black, '1' represents white, and '0.8' represents light gray.
Example
这是一个使用灰度级字符串指定 title color 的示例。
Here is an example of using the Gray level string for specifying the title color.
import matplotlib.pyplot as plt
import numpy as np
# Example data
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
# create a plot
fig, ax = plt.subplots(figsize=(7,4))
# Plotting the data
plt.plot(t, s)
# using the Gray level string for specifying title color
ax.set_title('Voltage vs. time chart', color='0.7')
# Show the plot
plt.show()
print('successfully used the Gray level string for specifying colors..')
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
successfully used the Gray level string for specifying colors..
The "Cn" Color notation
颜色规范“Cn”,即“C”后跟一个数字,该数字是默认属性循环 (rcParams["axes.prop_cycle"]) 中的索引,可用于指定 matplotlib 中的颜色。
A "Cn" color Spec, i.e., 'C' followed by a number, which is an index into the default property cycle (rcParams["axes.prop_cycle"]) can be used to specify the colors in matplotlib.
Example
在此示例中,使用 Cn 符号(color='C1')绘制一个绘图,该符号对应于默认属性循环中的第 2 个颜色。
In this example, a plot is drawn using the Cn notation (color='C1'), which corresponds to the 2nd color in the default property cycle.
import matplotlib.pyplot as plt
import numpy as np
# Example data
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
# create a plot
fig, ax = plt.subplots(figsize=(7,4))
# Cn notation for plot
ax.plot(t, .7*s, color='C1', linestyle='--')
# Show the plot
plt.show()
print('successfully used the Cn notation for specifying colors..')
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
successfully used the Cn notation for specifying colors..
The Single Letter String format
在 Matplotlib 中,单字母字符串用作简写符号来表示一组基本颜色。这些简写符号是 base colors 的一部分,作为 matplotlib.colors.BASE_COLORS 容器中的字典提供。每个字母都对应于一种特定的颜色。
In Matplotlib, single-letter strings are used as shorthand notations to represent a set of basic colors. These shorthand notations are part of the base colors available as a dictionary in matplotlib.colors.BASE_COLORS container. And each letter corresponds to a specific color.
单字母速记符号包括:“b”:蓝色,“g”:绿色,“r”:红色,“c”:青色,“m”:品红色,“y”:黄色,“k”:黑色以及“w”:白色。
The single-letter shorthand notations include: 'b': Blue, 'g': Green, 'r': Red, 'c': Cyan, 'm': Magenta, 'y': Yellow, 'k': Black, and 'w': White.
Example
在此示例中,每个基色被绘制为用其对应的单字母速记符号表示的条。
In this example, each base color is plotted as a bar with its corresponding single-letter shorthand notation.
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
# Get the base colors and their names
base_colors = mcolors.BASE_COLORS
color_names = list(base_colors.keys())
# Create a figure and axis
fig, ax = plt.subplots(figsize=(7, 4))
# Plot each color as a bar
for i, color_name in enumerate(color_names):
ax.bar(i, 1, color=base_colors[color_name], label=color_name)
# Set the x-axis ticks and labels
ax.set_xticks(np.arange(len(color_names)))
ax.set_xticklabels(color_names)
# Set labels and title
ax.set_title('Base Colors')
# Add legend
ax.legend()
# Show the plot
plt.show()
print('Successfully visualized all the available base colors..')
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
Successfully visualized all the available base colors..
Other formats
我们还可以使用“xkcd:”前缀、 xkcd color survey 中不区分大小写的颜色名称, X11/CSS4 ("html") 颜色名称和 Tableau Colors 。
Also we can use the Case-insensitive color name from the xkcd color survey with 'xkcd:' prefix, X11/CSS4 ("html") Color Names, and Tableau Colors.
Example
此示例演示了在 Matplotlib 绘图中使用不同颜色格式,包括 X11/CSS4 颜色、xkcd 颜色和 Tableau 颜色。
Here is an example that demonstrates the use of different color formats, including X11/CSS4 colors, xkcd colors, and Tableau Colors in a Matplotlib plot.
import matplotlib.pyplot as plt
import numpy as np
# Example data
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
# create a plot
fig, ax = plt.subplots(figsize=(7, 4))
# Plotting the data
plt.plot(t, s)
# 5) a named color:
ax.set_ylabel('Specifying color using the X11/CSS4 name', color='peachpuff')
# 6) a named xkcd color:
ax.set_xlabel('Specifying color name from the xkcd color survey', color='xkcd:crimson')
# 8) tab notation:
ax.set_title('Specifying color using the Tableau Colors', color='tab:orange')
plt.show()
print('Successfully used the X11/CSS4, xkcd, and Tableau Colors formats...')
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
Successfully used the X11/CSS4, xkcd, and Tableau Colors formats...
Darken or lighten a color
为了加深或减淡任何颜色,可以使用 plot() 方法的 alpha 参数,alpha 值越大,颜色越深,值越小,颜色越浅。
To darken or lighten any color, you can use the apha parameter of the plot() method, greater the aplha value will darker the color and smaller value will lighten the color.
Example
在此示例中,创建了两条具有不同 alpha 值的线,以复制线中更深和更浅的颜色。
Here is an example that creates a Plot of two lines with different value of alpha, to replicate darker and lighter color of the lines.
import numpy as np
from matplotlib import pyplot as plt
# Sample data
xs = np.linspace(-2, 2, 100)
ys = np.sin(xs)
# Create a figure
fig, ax = plt.subplots(figsize=(7, 4))
# plot two lines with different alpha values
ax.plot(xs, ys, c='red', lw=10, label="Darken")
ax.plot(xs+.75, ys+.75, c='red', lw=10, alpha=0.3, label="Lighten")
ax.legend(loc='upper left')
plt.show()
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −