【问题标题】:Using seaborn (or matplotlib) to create a scatterplot with the points made up of rectangles使用 seaborn(或 matplotlib)创建一个散点图,其中的点由矩形组成
【发布时间】:2021-06-21 07:53:32
【问题描述】:

正如标题所述,我想创建一个散点图,但我希望该图由矩形组成。到目前为止,显而易见的答案是将标记设置为“s”:

+---+---+-------+
| X | Y | Data  |
+---+---+-------+
| 1 | 1 |     0 |
| 1 | 2 |     1 |
+---+---+-------+

import seaborn as sns
sns.scatterplot(data=df, hue='Data', x='X', y='Y',
                legend='full', marker='s')

如果我想增加或减少 x 和 y 的每个点之间的距离(在图表上)怎么办?就像上面这张图一样,它们只是彼此相邻的两个相等的正方形,但是如果我希望它们是非常长或宽的矩形怎么办(但仍然只在点 (1,1) 和 (1,2) )?

最终目标是创建一个图,其中包含表示点的长(或宽,绝不是两者)矩形,就像上面的 df 一样。这正是我的想法。如果有更好的方法请推荐!

【问题讨论】:

    标签: python matplotlib graph seaborn


    【解决方案1】:

    您可以使用 x 值作为 x、y 值作为底部来创建条形图,并为条形设置您选择的矩形宽度和高度:

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'x': np.random.randint(1, 10, 20),
                       'y': np.random.randint(1, 10, 20),
                       'data': np.random.randint(0, 4, 20)})
    cmap = plt.get_cmap('plasma')
    norm = plt.Normalize(df['data'].min(), df['data'].max())
    c = [cmap(norm(d)) for d in df['data'].values]
    rwidth = 0.8  # desired width of the little rectangles
    rheight = 0.6  # desired height of the little rectangles
    
    fig, ax = plt.subplots()
    ax.bar(x=df['x'], height=rheight, bottom=df['y'] - rheight / 2, width=rwidth, color=c)
    ax.xaxis.set_major_locator(MultipleLocator(1))
    ax.yaxis.set_major_locator(MultipleLocator(1))
    ax.use_sticky_edges = False
    ax.legend(handles=[plt.Rectangle((0, 0), 0, 0, label=d, color=cmap(norm(d)))
                       for d in range(df['data'].min(), df['data'].max() + 1)])
    plt.show()
    

    【讨论】:

    • 我知道为什么我没有想到使用条形图。出于某种原因,我非常专注于使用散点图,哈哈。我试试这个,谢谢!
    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 2021-10-10
    • 2023-02-01
    • 1970-01-01
    • 2019-09-26
    • 2023-01-20
    • 2020-12-04
    相关资源
    最近更新 更多