Matplotlib 简明教程
Matplotlib - Background Colors
What are Background Colors in Matplotlib?
Matplotlib 提供广泛的选项来控制背景颜色,使用户能够自定义绘图和图形的可视外观。背景颜色在增强可视化的美感和可读性、为所显示数据设置基调和情绪方面发挥着至关重要的作用。
Matplotlib provides extensive options to control background colors enabling users to customize the visual appearance of plots and figures. The background color plays a crucial role in enhancing the aesthetics and readability of visualizations, setting the tone and mood for the displayed data.
以下是 Matplotlib 库中可用的不同功能。我们逐一详细查看。
The following are the different features available in the Background colors of Matplotlib library. Let’s see each one in detailed view.
Figure and Plot Background Color
图形的背景颜色涵盖了绘制绘图的整个区域。默认情况下它通常是白色,但可以使用 plt.figure(facecolor='color_name') 或 plt.gcf().set_facecolor('color_name') 进行更改。这会影响绘图周围的区域。
The figure’s background color encompasses the entire area where plots are rendered. By default it’s often white but it can be changed using plt.figure(facecolor='color_name') or plt.gcf().set_facecolor('color_name'). This affects the area around the plots.
另一方面,绘图背景颜色是指绘图轴内的区域。可以通过 plt.gca().set_facecolor('color_name') 更改它,方法是在实际绘图中提供不同的背景颜色。
The plot background color on the other hand refers to the area within the plot’s axes. It can be altered with plt.gca().set_facecolor('color_name') by providing a different background color within the actual plot.
Changing Figure Bacground color
在此示例中,演示了如何使用 Matplotlib 库设置图形的背景颜色。
In this example demonstrating how to set the background color for the figure using Matplotlib library.
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()
Changing Plot Area Background Color
在此示例中,我们使用 plt.gca().set_facecolor('lightgreen') 专门设置绘图区域的背景颜色。
In this example we use plt.gca().set_facecolor('lightgreen') to set the background color for the plot area specifically.
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()
Stylesheets for Background Colors
Matplotlib 提供了样式表,其中提供了预定义的配置,包括背景颜色。 'dark_background', 'ggplot' 或 'seaborn' 等样式表有独特的配色方案,它们会影响绘图、图形和其他元素的背景颜色。
Matplotlib offers stylesheets that provide predefined configurations including background colors. Stylesheets like 'dark_background', 'ggplot' or 'seaborn' have distinctive color schemes that affect the background color of plots, figures and other elements.
样式表不仅修改了背景颜色,还包括各种其他风格元素,例如线条颜色、文本大小和网格样式。通过尝试不同的样式表,我们可以快速探索和可视化不同样式如何影响我们绘图的外观。
Stylesheets not only modify the background colors but also encompass various other stylistic elements such as line colors, text sizes and grid styles. Experimenting with different stylesheets allows us to quickly explore and visualize how different styles affect the appearance of our plots.
Example
以下示例展示了如何使用 Matplotlib 中的样式表来修改
Here’s an example showcasing how stylesheets in Matplotlib can be used to modify
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()
Impact on Visualization
背景颜色会影响数据的视觉感知。深色背景可能会突出显示明亮对比的数据,而浅色背景通常提供干净且传统的观感,适用于大多数情况。应仔细选择背景颜色,以确保观众的可读性和可访问性。
Background colors influence the visual perception of data. Dark backgrounds might emphasize bright or contrasting data while light backgrounds often offer a clean and conventional look suitable for most contexts. Background colors should be chosen carefully to ensure readability and accessibility for viewers.
Customization and Color Representation
我们可以使用各种表示形式自定义背景颜色,例如颜色名称(“蓝色”、“红色”)、十六进制字符串(“#RRGGBB”)、RGB 元组 0.1、0.2、0.5 或带 alpha 透明度的 RGBA 元组 0.1、0.2、0.5、0.3。
We can customize background colors using various representations such as color names ('blue', 'red'), hexadecimal strings ('#RRGGBB'), RGB tuples 0.1, 0.2, 0.5, or RGBA tuples with alpha transparency 0.1, 0.2, 0.5, 0.3.
这些颜色字符串表示形式提供了指定绘图中各种元素颜色的灵活性,允许我们精确控制可视化的视觉外观。我们可以使用命名颜色、十六进制字符串、RGB 元组或 RGBA 值为 Matplotlib 绘图中的不同元素自定义颜色。
These color string representations offer flexibility in specifying colors for various elements within the plot by allowing us to precisely control the visual appearance of our visualizations. We can use named colors, hexadecimal strings, RGB tuples or RGBA values to customize colors for different elements in Matplotlib plots.
Customizing with Color Strings
我们可以直接使用颜色名称或十六进制字符串设置背景颜色。
We can directly use color names or hexadecimal strings to set the background color.
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()
Customization Options
我们还可以使用颜色字符串或 RGB 值自定义其他元素,例如线条颜色、标记颜色,甚至修改绘图中特定文本元素的颜色。
We can also customize other elements using color strings or RGB values such as line colors, marker colors or even modifying the color of specific text elements in the plot.
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()
Importance of Background Colors
背景颜色的选择显著影响可视化的美感和解释。它会影响可读性、视觉对比度和显示数据的总体印象。背景颜色的选择应以背景、受众和可视化的具体目的为指导。
The choice of background color significantly impacts the aesthetics and interpretation of visualizations. It can affect readability, visual contrast and the overall impression of the displayed data. Context, audience and the specific purpose of the visualization should guide the selection of background colors.
Use Cases
Contrast and Visibility - 可以调整数据元素和背景之间的对比度,以突出显示或弱化某些信息。
Contrast and Visibility − Contrast between data elements and the background can be adjusted to highlight or de-emphasize certain information.
Themes and Branding - 背景颜色可以通过确保多个可视化的协调性,与品牌或主题考量保持一致。
Themes and Branding − Background colors can align with branding or thematic considerations by ensuring consistency across multiple visualizations.
Accessibility - 选择合适的背景颜色对于确保可访问性至关重要,特别是对于有视觉缺陷的人来说。
Accessibility − Selecting appropriate background color is very crucial for ensuring accessibility, especially for individuals with visual impairments.
Matplotlib 提供了多种选项来控制绘图和图形中的背景颜色。这些选择对可视化的美观性、可读性和解释具有重大影响,使其成为创建有效且引人入胜的绘图的基本方面。适当选择背景颜色可以提升数据表征的整体吸引力和沟通力。
Matplotlib offers diverse options for controlling background colors in plots and figures. These choices have a substantial impact on the aesthetics, readability and interpretation of visualization by making them a fundamental aspect of creating effective and engaging plots. Properly chosen background colors enhance the overall appeal and communication of data representations.
Change the default background color
在此示例中,我们将更改 Matplotlib 绘图的默认背景颜色。
In this example we will change the default background color for Matplotlib plots.
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()
Change axes background color
在此示例中,我们通过使用 set_facecolor() 方法更改了坐标轴的背景颜色。
Here in this example we change the axes background color by using the set_facecolor() method.
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()
Set the background color of a column in a matplotlib table
这是在 matplotlib 表格中设置列背景颜色的参考示例。
This is the reference example for setting the background color of a column in a matplotlib table.
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()