【问题标题】:Pandas Scatterplot with colorcoded points带有颜色编码点的 Pandas 散点图
【发布时间】:2017-07-27 09:43:08
【问题描述】:

我想从 Dataframe 制作散点图,其中每个点都以独特的颜色可视化,具体取决于该值出现的频率。例如,我有以下数据框,由两个数值列表组成:

df = pd.DataFrame({'width': image_widths, 'height': image_heights})
df.head(10)
   height  width
0    1093    640
1    1136    639
2    1095    640
3    1136    639
4    1095    640
5    1100    640
6    1136    640
7    1136    639
8    1136    640
9    1031    640

现在,如您所见,一些值对出现了多次。例如 (1095/640) 出现在索引 2 和 4。我如何给这个点一个代表“两次出现”的颜色。 如果颜色是从连续光谱中自动挑选出来的,就像在彩条图中一样,那就更好了。这样,颜色阴影就已经给您对频率的印象,而不是通过手动查找颜色代表它的方式。

我也很欣赏着色的替代方法是将出现频率编码为点的半径。

编辑:

为了说明我的问题,我发现df.groupby(['width','height']).size() 给了我所有组合的计数。 现在我缺乏将这些信息与图中点的颜色(或大小)联系起来的技能。

【问题讨论】:

  • 您可以为每个点分配基于高度和宽度的红色和绿色值以及基于频率的蓝色值(或 alpha)。或者,您可以使用每个点的填充颜色、描边颜色和 alpha。有很多选择,这完全取决于您。
  • @alec_djinn:宽度有两个以上的值,所以我必须分配很多值。不幸的是,在示例中只出现了这两个值。此外,将来很有可能会附加更多具有未见尺寸的点。但无论如何,感谢您的评论。
  • R、G、B通道各有256个值...

标签: python pandas data-visualization scatter-plot


【解决方案1】:

所以让我们把它变成真正的Minimal, Complete, and Verifiable example

import matplotlib.pyplot as plt
import pandas as pd

image_heights = [1093, 1136, 1095, 1136, 1095, 1100, 1136, 1136, 1136, 1031]
image_widths = [640, 639, 640, 639, 640, 640, 640, 639, 640, 640]
df = pd.DataFrame({'width': image_widths, 'height': image_heights})
print(df)

   width  height
0    640    1093
1    639    1136
2    640    1095
3    639    1136
4    640    1095
5    640    1100
6    640    1136
7    639    1136
8    640    1136
9    640    1031

您需要DataFrame 中的大小(计数)以及宽度和高度:

plot_df = df.groupby(['width','height']).size().reset_index(name='count')
print(plot_df)

   width  height  count
0    639    1136      3
1    640    1031      1
2    640    1093      1
3    640    1095      2
4    640    1100      1
5    640    1136      2

如果您使用DataFrame.plot.scatter,散点图中的颜色和大小由cs 关键字控制:

plot_df.plot.scatter(x='height', y='width', s=10 * plot_df['count']**2,
                     c='count', cmap='viridis')

【讨论】:

  • 非常简洁的答案! ++ :)
  • @tontus 它对我有用。也许用minimal reproducible example 提出另一个问题。如果您在此处放置链接,我将很乐意查看。
猜你喜欢
  • 2016-05-20
  • 2015-05-28
  • 1970-01-01
  • 2019-05-25
  • 2016-12-30
  • 1970-01-01
  • 2020-02-15
  • 2021-11-01
相关资源
最近更新 更多