首页 > 解决方案 > 具有 4 个视觉编码的 Matplotlib 散点图

问题描述

第一步是一个带有几列的熊猫数据框。

to_numpy()我做的第二步是使用函数将此 Dataframe 的某些列转换为 Numpy 数组。

我检索到类似的东西:

[[100 200 3.5 1] [100 200 3.5 1] [100 300 6.2 1] [200 125 4.2 1] [100 300 6.2 1] [100 200 3.5 1]]

第一个元素想象是一个起源 id 第二个元素是一个命运 id 第三个是起源和命运之间的距离,第四个只是一个计数器(1 个元素)(我包含它只是因为我认为这可能是必需的计算元素。如果您提出的解决方案不使用它,请忽略它)

我想要一个具有以下规格的散点图:

我已经尝试过,但我无法在这个情节中包含所有先决条件。如何在 matplotlib 中实现这一点?或者有没有其他更简单的方法直接使用熊猫?

标签: pythonpandasmatplotlibscatter-plot

解决方案


如果我正确理解了您的要求,这应该可以解决问题:

import matplotlib.pyplot as plt
import numpy as np

data = np.array([[100,200,3.5,1],[100,200,3.5,1],[100,300,6.2,1],[200,125,4.2,1],[100,300,6.2,1],[100,200,3.5,1]])

unique, counts =  np.unique(data, axis=0,  return_counts=True)  
x = unique[:,0]
y = unique[:,1]
c = unique[:,2]
## figure out a nice looking scaling factor here
#  and remember that the scatter point size is supposed to be an area,
#  hence squaring a base factor is ideal
s = (counts*10)**2 
fig, ax = plt.subplots()

sca = ax.scatter(x,y,c=c,s=s)
plt.colorbar(sca)

plt.show()

产生:

散点图


推荐阅读