首页 > 解决方案 > 使用 seaborn(或 matplotlib)创建一个散点图,其中的点由矩形组成

问题描述

正如标题所述,我想创建一个散点图,但我希望该图由矩形组成。到目前为止,显而易见的答案是将标记设置为“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 一样。这正是我的想法。如果有更好的方法请推荐!

标签: pythonmatplotlibgraphseaborn

解决方案


您可以使用 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()

带矩形的散点图


推荐阅读