【问题标题】:Add scatterplot with different colors and size based on volume?根据体积添加不同颜色和大小的散点图?
【发布时间】:2020-01-10 14:04:55
【问题描述】:

我想用 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 型为蓝色,圆点的大小应根据体积不同而不同!知道如何实现这一目标或在某处提供指南吗?

【问题讨论】:

  • 我们可以从您目前所拥有的开始。你是如何创建散点图的?
  • 你看过哪个other questions?他们在多大程度上没有帮助?

标签: python pandas matplotlib


【解决方案1】:

仅使用 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'))

结果:

【讨论】:

  • 你是什么样的巫师?=) 完美!我现在将尝试逐行理解,并以谦虚的问候感谢您!
  • @CodeDifferent:请注意,您正在为 stackoverflow 的主要问题之一做出贡献,即有用信息分布在越来越多的问题中,这使得未来的读者更难找到所需的内容。相反,如果您对关于该主题的众多其他问题之一给出了这个答案,那么对每个人都会更有帮助。
  • @ImportanceOfBeingErnest :相信我,我已经看过了。如果您很友善,请添加一个帖子,其中显示特定问题并提供解决方案?在这种情况下,我遇到了基于列中 2 个不同值的 2 种不同颜色的问题,并且 CodeDifferent 通过使用 .map 提出了一个非常好的解决方案。我不经常使用stackoverflow,只有当我被卡住并且在阅读帖子后找不到问题的解决方案时。老实说,我没有意识到问题出在哪里......CodeDifferent 让我很开心并降低了我的血压 =)
  • Thisthis 例如。还有很多其他的。就个人而言,你可以感谢任何回答的人,当然,但是社区,尤其是下一个有类似问题的人,现在需要查看另一个帖子,而不是在一个地方找到所有好的解决方案。
猜你喜欢
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
相关资源
最近更新 更多