设置颜色 Alpha 值的方法#

比较通过alpha关键字参数和通过 Matplotlib 颜色格式之一设置 Alpha 的方法。通常,alpha关键字是为颜色添加透明度的唯一工具。在某些情况下,(matplotlib_color, alpha)颜色格式提供了一种简单的方法来微调 Figure 的外观。

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility.
np.random.seed(19680801)

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4))

x_values = [n for n in range(20)]
y_values = np.random.randn(20)

facecolors = ['green' if y > 0 else 'red' for y in y_values]
edgecolors = facecolors

ax1.bar(x_values, y_values, color=facecolors, edgecolor=edgecolors, alpha=0.5)
ax1.set_title("Explicit 'alpha' keyword value\nshared by all bars and edges")


# Normalize y values to get distinct face alpha values.
abs_y = [abs(y) for y in y_values]
face_alphas = [n / max(abs_y) for n in abs_y]
edge_alphas = [1 - alpha for alpha in face_alphas]

colors_with_alphas = list(zip(facecolors, face_alphas))
edgecolors_with_alphas = list(zip(edgecolors, edge_alphas))

ax2.bar(x_values, y_values, color=colors_with_alphas,
        edgecolor=edgecolors_with_alphas)
ax2.set_title('Normalized alphas for\neach bar and each edge')

plt.show()
Explicit 'alpha' keyword value shared by all bars and edges, Normalized alphas for each bar and each edge

参考资料

本示例展示了以下函数、方法、类和模块的使用

Sphinx-Gallery 生成的画廊