如何使用归一化标记透明度创建散点图

How to create a scatter plot with normalized marker transparencies

提问人:VERBOSE 提问时间:9/29/2023 最后编辑:Trenton McKinneyVERBOSE 更新时间:9/29/2023 访问量:58

问:

我有这个数据帧:

import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(seed=111)
rints = rng.integers(low=0, high=1000, size=(5,5))
df = pd.DataFrame(rints)

     0    1    2    3    4
0  474  153  723  169  713
1  505  364  658  854  767
2  718  109  141  797  463
3  968  130  246  495  197
4  450  338   83  715  787

我正在尝试按原样绘制它并设置标记的大小及其透明度:

ox = np.arange(len(df))
x = np.tile(ox[:, np.newaxis], (1, len(ox)))
y = np.tile(ox, (len(df), 1))

plt.scatter(x, y, marker='o', color='tab:orange', ec='k', ls='--', s=df.values)

for ix,iy,v in zip(x.ravel(), y.ravel(), df.values.ravel()):
    plt.annotate(str(v), (ix,iy), textcoords='offset points', xytext=(0,10), ha='center')
        
plt.axis("off")
plt.margins(y=0.2)
plt.show()

只有两个问题:

  1. 该图没有反映真实的数据帧形状,我觉得它被转置了
  2. 我不知道如何调整散点的透明度,就像我调整大小一样
    • 刚好与单元格的值成正比(就像我对大小所做的那样)。较低值为浅色,较高值为强色。

enter image description here

python pandas matplotlib 散点图 透明度

评论


答:

2赞 mozway 9/29/2023 #1

为了避免转置,请正确映射 和 (这里使用 numpy.meshgrid),并使用 scatter 的参数 (matplotlib ≥ 3.4):xyalpha

# inverting df to have the same row order
df2 = df[::-1]

# computing meshgrid
x, y = np.meshgrid(range(df.shape[0]), range(df.shape[1]))

# plotting
plt.scatter(x, y, marker='o', color='tab:orange', ec='k', ls='--',
            s=df2, alpha=df2.div(np.max(df2)))

for ix,iy,v in zip(x.ravel(), y.ravel(), df2.to_numpy().ravel()):
    plt.annotate(str(v), (ix,iy), textcoords='offset points',
                 xytext=(0,10), ha='center')
        
plt.axis("off")
plt.margins(y=0.2)
plt.show()

输出:

enter image description here

评论

0赞 VERBOSE 9/29/2023
你的前两行看起来既简单又复杂。网格的东西看起来很可怕,但感谢您链接文档。只是一个小问题,当文档需要浮点数时,我们如何将数据帧作为 alpha 的值传递?谢谢你,我的朋友。
1赞 mozway 9/29/2023
我同意该文档在这里具有误导性。关于形状,它与 和 相同。xy