python - 使用 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 一样。这正是我的想法。如果有更好的方法请推荐!
解决方案
您可以使用 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()
推荐阅读
- css - 如何从古腾堡编辑器中居中表格
- r - 在R中循环月份名称
- reactjs - 将 URL 路径指定为手动构建的 REACT SSR 应用程序的变量(即不使用 NextJS )
- javascript - 如何创建多个嵌套列表
- json - NiFi - 将 json 中的逗号分隔字符串转换为数组
- python - 如何将具有命令行功能的 Python 包从 bash 迁移到 zsh
- listbox - OfficeJS 从下拉列表内容控件中读取文本
- python - 如何在不截断旧数据的情况下从 pandas 数据框中追加一个表
- shiny - 当我在下拉菜单中选择输入值时,输出结果不会改变
- javascript - 在可见性切换上调整 div 的大小(在 HTML + 纯 JS 中)?