根据体积添加具有不同颜色和大小的散点图?

时间:2019-09-08 15:26:47

标签: python pandas matplotlib

我想用matplotlib和一个简单的pandas数据框创建一个散点图。已经测试了几乎所有内容,但没有任何效果,说实话,我刚刚在matplotlib上订购了一本书。

数据框看起来像这样

           Time     Type    Price          Volume
0   03:03:26.936    B   1.61797     1000000
1   03:41:06.192    B   1.61812     1000000
2   05:59:12.799    B   1.62280     410000
3   05:59:12.814    B   1.62280     390000
4   06:43:33.607    B   1.62387     1000000
5   06:43:33.621    S   1.62389     500000
6   06:47:36.834    B   1.62412     1000000
7   08:15:13.903    B   1.62589     1000000
8   09:15:31.496    S   1.62296     500000
9   10:29:24.072    S   1.61876     500000
10  10:49:08.619    S   1.61911     1000000
11  11:07:01.213    S   1.61882     1000000
12  11:07:01.339    S   1.61880     200000
13  11:23:00.300    S   1.61717     1000000

类型B的颜色应为绿色,类型S的蓝色和点的大小应根据体积而不同!知道如何在某个地方实现此目标或指南吗?

1 个答案:

答案 0 :(得分:2)

仅使用matplotlib的解决方案:

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

# Your Time column is stored as strings. Convert them to Timestamp
# so matplotlib can plot a proper timeline
times = pd.to_datetime(df['Time'])

# Set the marker's color: 'B' is green, 'S' is blue
colors = df['Type'].map({
    'B': 'green',
    'S': 'blue'
})

# Limit the x-axis from 0:00 to 24:00
xmin = pd.Timestamp('0:00')
xmax = xmin + pd.Timedelta(days=1)

# Make the plot
fig, ax = plt.subplots(figsize=(6,4))
ax.scatter(x=times, y=df['Price'], c=colors, s=df['Volume'] / 2000, alpha=0.2)
ax.set(
    xlabel='Time',
    xlim=(xmin, xmax),
    ylabel='Price'
)
ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))

结果:

Scatter Plot