python - 如何使 Matplotlib 散点图作为一个整体透明?

标签 python matplotlib transparency scatter-plot

我正在使用 Matplotlib(python 3.4.0,matplotlib 1.4.3,在 Linux Mint 17 上运行)制作一些散点图。为每个点单独设置 alpha 透明度非常容易;有什么方法可以将它们设置为一组,以便同一组中的两个重叠点不会改变颜色?

示例代码:

import matplotlib.pyplot as plt
import numpy as np

def points(n=100):
    x = np.random.uniform(size=n)
    y = np.random.uniform(size=n)
    return x, y
x1, y1 = points()
x2, y2 = points()
fig = plt.figure(figsize=(4,4))
ax = fig.add_subplot(111, title="Test scatter")
ax.scatter(x1, y1, s=100, color="blue", alpha=0.5)
ax.scatter(x2, y2, s=100, color="red", alpha=0.5)
fig.savefig("test_scatter.png")

此输出结果:

enter image description here

但我想要更像这样的东西:

enter image description here

我可以通过另存为 SVG 并在 Inkscape 中手动分组,然后设置透明度来解决问题,但我真的更喜欢我可以编码的东西。有什么建议吗?

最佳答案

是的,有趣的问题。你可以用 Shapely 得到这个散点图.这是代码:

import matplotlib.pyplot as plt
import matplotlib.patches as ptc
import numpy as np
from shapely.geometry import Point
from shapely.ops import cascaded_union

n = 100
size = 0.02
alpha = 0.5

def points():
    x = np.random.uniform(size=n)
    y = np.random.uniform(size=n)
    return x, y

x1, y1 = points()
x2, y2 = points()
polygons1 = [Point(x1[i], y1[i]).buffer(size) for i in range(n)]
polygons2 = [Point(x2[i], y2[i]).buffer(size) for i in range(n)]
polygons1 = cascaded_union(polygons1)
polygons2 = cascaded_union(polygons2)

fig = plt.figure(figsize=(4,4))
ax = fig.add_subplot(111, title="Test scatter")
for polygon1 in polygons1:
    polygon1 = ptc.Polygon(np.array(polygon1.exterior), facecolor="red", lw=0, alpha=alpha)
    ax.add_patch(polygon1)
for polygon2 in polygons2:
    polygon2 = ptc.Polygon(np.array(polygon2.exterior), facecolor="blue", lw=0, alpha=alpha)
    ax.add_patch(polygon2)
ax.axis([-0.2, 1.2, -0.2, 1.2])

fig.savefig("test_scatter.png")

结果是:

Test scatter

关于python - 如何使 Matplotlib 散点图作为一个整体透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30108372/

相关文章:

python - 如何消除 QTableWidget 中的空白?

python - matplotlib:重新缩放轴标签

python - 在 python 中使用 matplotlib 绘制频率线图

python - 来自事件坐标的 Matplotlib 日期时间

C# Alpha Blend 透明 PictureBox

C# Winforms 透明控件允许点击

python - 生成所有 Euler Bricks

python - 属性错误: 'Corn' object has no attribute '_Plant__symbol'

python - 为 mariadb 10 Ubuntu 13.10 安装 mysqldb python 接口(interface)时找不到 mysql_config

ios - 如何使用 OpenGL 避免透明度重叠?