来自pandas数据帧的不同大小,标记和颜色的散点图

问题描述 投票:6回答:2

我正在尝试为每个点做一个速度超过米的散点图,其中标记表示不同的类型,大小表示不同的重量,颜色表示一个点超过10分钟的比例。但是,到目前为止我只能按尺寸绘制。

任何帮助都非常感谢。

x = {'speed': [10, 15, 20, 18, 19], 'meters' : [122, 150, 190, 230, 300], 'type': ['phone', 'phone', 'gps', 'gps', 'car'], 'weight': [0.2, 0.3, 0.1, 0.85, 0.0], 'old': [1, 2, 4, 5, 8]}

m = pd.DataFrame(x)

plt.scatter(m.meters, m.speed, s = 30* m.weight)

mkr_dict = {'gps': 'x', 'phone': '+', 'car': 'o'}

   meters  speed   type  weight  old
0     122     10  phone    0.20    1
1     150     15  phone    0.30    2
2     190     20    gps    0.10    4
3     230     18    gps    0.85    5
4     300     19    car    0.00    8

更新的问题:

我正在尝试将colorbar添加到基于旧的颜色标度。当我绘制整个数据集时,但是在尝试为每个子集添加标记后失败了。任何的想法?

plt.scatter(m.meters, m.speed, s = 30* m.weight, c=m.old)
cbar = plt.colorbar(ticks = [0, 5, 10])
cbar.ax.set_yticklabels(['New','5mins', '10mins'])

TypeError:首先必须set_array为mappable

python matplotlib scatter-plot marker colorbar
2个回答
12
投票

scatter一次只能做一种标记,所以你必须分别绘制不同的类型。幸运的是,熊猫很容易:

import matplotlib.pyplot as plt
import pandas as pd
x = {'speed': [10, 15, 20, 18, 19],
     'meters' : [122, 150, 190, 230, 300],
     'type': ['phone', 'phone', 'gps', 'gps', 'car'],
     'weight': [0.2, 0.3, 0.1, 0.85, 0.0],
     'old': [1, 2, 4, 5, 8]}

m = pd.DataFrame(x)
mkr_dict = {'gps': 'x', 'phone': '+', 'car': 'o'}
for kind in mkr_dict:
    d = m[m.type==kind]
    plt.scatter(d.meters, d.speed, 
                s = 100* d.weight, 
                c = d.old, 
                marker = mkr_dict[kind])
plt.show()

......车在哪里?好吧,原始测试数据中的重量是0.0,我们使用重量作为标记大小,所以:看不到它。


5
投票

如果您只有几个点,就像这里一样,您可以将一个浮点列表传递给c参数:

colors = ['r', 'b', 'k', 'g', 'm']
plt.scatter(m.meters, m.speed, s=30*m.weight, vmin=0, vmax=10, cmap=cm)

根据给定的顺序给你的积分着色。或者,要使用色彩映射:

cm = plt.cm.get_cmap('hot')  # or your colormap of choice
plt.scatter(m.meters, m.speed, s=30*m.weight, c=m.old, cmap=cm)

要更改标记形状,您需要添加自己的Patches,或一次添加一个点:例如

markers = ['^', 'o', 'v', 's', 'd']
for px, py, c, s, t in zip(m.meters, m.speed, m.old, m.weight, markers):
    plt.scatter(px, py, marker=t, c=cm(c/10.), vmin=0, vmax=10, s=400*s+100)
plt.show()

(我已将m.weight缩放到不同的范围以查看第5个点,否则其大小为0.0)。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.