基于matplotlib的向日葵散点图

2024-05-21 01:01:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有兴趣构建一个向日葵散点图(例如,http://www.jstatsoft.org/v08/i03/paper[PDF link])。在我编写自己的实现之前,有人知道现有的实现吗?我知道Stata和R中的函数,但正在matplotlib中寻找一个。在

谢谢。在


Tags: 函数orghttppdfmatplotlibwwwlinkpaper
1条回答
网友
1楼 · 发布于 2024-05-21 01:01:15

我不知道有什么matplotlib实现,但不难做到。在这里,我让hexbin进行计数,然后遍历每个单元格并添加适当数量的花瓣:

enter image description here

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

np.random.seed(0)
n = 2000
x = np.random.standard_normal(n)
y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)

cmap = colors.ListedColormap(['white', 'yellow', 'orange'])
hb = plt.hexbin(x,y, bins='log', cmap=cmap, gridsize=20, edgecolor='gray')
plt.axis([-2, 2, -12, 12])
plt.title("sunflower plot")

counts = hb.get_array()
coords = hb.get_offsets()

for i, count in enumerate(counts):
    x, y = coords[i,:]
    count = int(10**count)
    if count>3 and count<=12:
        n = count // 1
        if n>1:
            plt.plot([x], [y], 'k.')
            plt.plot([x], [y], marker=(n, 2), color='k', markersize=18)
    if count>12:
        n = count // 5
        if n>1:
            plt.plot([x], [y], 'k.')
            plt.plot([x], [y], marker=(n, 2), color='k', markersize=18)

plt.show()

这里黄色是1花瓣=1,橙色是1花瓣=5。

一个明显需要改进的地方是使用colormap。例如,您想预置颜色边界还是根据数据计算它们?在这里,我只是略显模糊:我使用bins='log'只是为了得到我使用的特定样本的黄色和橙色单元格之间的合理比例;而且我硬编码了白色、黄色和橙色单元格之间的边界(3和12)。

能够在matplotlib中使用元组来指定标记特征,这使得绘制所有不同的花瓣编号变得非常容易。

相关问题 更多 >