Matplotlib 简明教程

Matplotlib - Background Colors

What are Background Colors in Matplotlib?

Matplotlib 提供广泛的选项来控制背景颜色,使用户能够自定义绘图和图形的可视外观。背景颜色在增强可视化的美感和可读性、为所显示数据设置基调和情绪方面发挥着至关重要的作用。

以下是 Matplotlib 库中可用的不同功能。我们逐一详细查看。

Figure and Plot Background Color

图形的背景颜色涵盖了绘制绘图的整个区域。默认情况下它通常是白色,但可以使用 plt.figure(facecolor='color_name')plt.gcf().set_facecolor('color_name') 进行更改。这会影响绘图周围的区域。

另一方面,绘图背景颜色是指绘图轴内的区域。可以通过 plt.gca().set_facecolor('color_name') 更改它,方法是在实际绘图中提供不同的背景颜色。

Changing Figure Bacground color

在此示例中,演示了如何使用 Matplotlib 库设置图形的背景颜色。

import matplotlib.pyplot as plt
import numpy as np
# Generating data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Changing Figure Background Color
plt.figure(facecolor='lightblue')  # Set figure background color
plt.plot(x, y)
plt.title('Figure Background Color Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
figure plot

Changing Plot Area Background Color

在此示例中,我们使用 plt.gca().set_facecolor('lightgreen') 专门设置绘图区域的背景颜色。

import matplotlib.pyplot as plt
import numpy as np
# Generating data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Changing plot area Background Color
plt.plot(x, y)
plt.gca().set_facecolor('lightgreen')  # Set plot area background color
plt.title('Plot Area Background Color Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
plot areas

Stylesheets for Background Colors

Matplotlib 提供了样式表,其中提供了预定义的配置,包括背景颜色。 'dark_background', 'ggplot''seaborn' 等样式表有独特的配色方案,它们会影响绘图、图形和其他元素的背景颜色。

样式表不仅修改了背景颜色,还包括各种其他风格元素,例如线条颜色、文本大小和网格样式。通过尝试不同的样式表,我们可以快速探索和可视化不同样式如何影响我们绘图的外观。

Example

以下示例展示了如何使用 Matplotlib 中的样式表来修改

import matplotlib.pyplot as plt
import numpy as np
# Generating data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Plot using different stylesheets
stylesheets = ['ggplot', 'dark_background', 'seaborn-poster']
for style in stylesheets:
   plt.style.use(style)  # Apply the selected stylesheet
   plt.plot(x, y)
   plt.title(f'Plot with {style.capitalize()} Stylesheet')
   plt.xlabel('X-axis')
   plt.ylabel('Y-axis')
   plt.show()
style sheets
style sheets2
style sheets3

Impact on Visualization

背景颜色会影响数据的视觉感知。深色背景可能会突出显示明亮对比的数据,而浅色背景通常提供干净且传统的观感,适用于大多数情况。应仔细选择背景颜色,以确保观众的可读性和可访问性。

Customization and Color Representation

我们可以使用各种表示形式自定义背景颜色,例如颜色名称(“蓝色”、“红色”)、十六进制字符串(“#RRGGBB”)、RGB 元组 0.1、0.2、0.5 或带 alpha 透明度的 RGBA 元组 0.1、0.2、0.5、0.3。

这些颜色字符串表示形式提供了指定绘图中各种元素颜色的灵活性,允许我们精确控制可视化的视觉外观。我们可以使用命名颜色、十六进制字符串、RGB 元组或 RGBA 值为 Matplotlib 绘图中的不同元素自定义颜色。

Customizing with Color Strings

我们可以直接使用颜色名称或十六进制字符串设置背景颜色。

import matplotlib.pyplot as plt
import numpy as np
# Generating data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Customizing with color strings
plt.figure(facecolor='green')  # Set figure background color using color name
plt.plot(x, y)
plt.title('Customizing with Color Strings')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
customize

Customization Options

我们还可以使用颜色字符串或 RGB 值自定义其他元素,例如线条颜色、标记颜色,甚至修改绘图中特定文本元素的颜色。

import matplotlib.pyplot as plt
import numpy as np
# Generating data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Customizing with color strings
plt.figure(facecolor='lightblue')  # Set figure background color using color name
plt.plot(x, y, color='orange')  # Set line color using a color name
plt.scatter(x, y, color='#00FF00')  # Set marker color using hexadecimal color string
plt.xlabel('X-axis', color='red')  # Set x-axis label color using a color name
plt.ylabel('Y-axis', color=(0.5, 0.1, 0.7))  # Set y-axis label color using RGB tuple
plt.show()
customize options

Importance of Background Colors

背景颜色的选择显著影响可视化的美感和解释。它会影响可读性、视觉对比度和显示数据的总体印象。背景颜色的选择应以背景、受众和可视化的具体目的为指导。

Use Cases

Contrast and Visibility - 可以调整数据元素和背景之间的对比度,以突出显示或弱化某些信息。

Themes and Branding - 背景颜色可以通过确保多个可视化的协调性,与品牌或主题考量保持一致。

Accessibility - 选择合适的背景颜色对于确保可访问性至关重要,特别是对于有视觉缺陷的人来说。

Matplotlib 提供了多种选项来控制绘图和图形中的背景颜色。这些选择对可视化的美观性、可读性和解释具有重大影响,使其成为创建有效且引人入胜的绘图的基本方面。适当选择背景颜色可以提升数据表征的整体吸引力和沟通力。

Change the default background color

在此示例中,我们将更改 Matplotlib 绘图的默认背景颜色。

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
ax = plt.gca()
print("Default face color is: ", ax.get_facecolor())
plt.subplot(121)
plt.plot(np.random.rand(10), np.random.rand(10))
plt.title("With default face color")
plt.subplot(122)
ax = plt.gca()
ax.set_facecolor("orange")
plt.plot(np.random.rand(10), np.random.rand(10))
plt.title("With customize face color")
plt.show()
default background

Change axes background color

在此示例中,我们通过使用 set_facecolor() 方法更改了坐标轴的背景颜色。

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
ax = plt.gca()
ax.set_facecolor("orange")
x = np.linspace(-2, 2, 10)
y = np.exp(-x)
plt.plot(x, y, color='red')
plt.show()
axes background

Set the background color of a column in a matplotlib table

这是在 matplotlib 表格中设置列背景颜色的参考示例。

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
columns = ('name', 'age', 'marks', 'salary')
cell_text = [["John", "23", "98", "234"], ["James", "24", "90", "239"]]
colors = [["red", "yellow", "blue", "green"], ["blue", "green", "yellow", "red"]]
fig, ax = plt.subplots()
the_table = ax.table(cellText=cell_text, cellColours=colors, colLabels=columns, loc='center')
ax.axis('off')
plt.show()
table