Pandas 带有颜色编码点的散点图
Pandas Scatterplot with colorcoded points
我想从 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 处。如何为该点指定代表 "Two occurences" 的颜色。
如果颜色是从连续光谱中自动选取的,就像在彩条图中那样,那就更好了。这样颜色阴影就已经给了你频率的印象,而不是通过手动查找颜色代表它。
另一种着色方法是将出现频率编码为圆点的半径。
编辑:
为了具体说明我的问题,我发现 df.groupby(['width','height']).size()
给出了所有组合的计数。
现在我缺乏 link 这些信息与图中点的颜色(或大小)的技能。
所以让我们把它变成真的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
散点图中的颜色和大小由 c
和 s
关键字控制,如果您使用 DataFrame.plot.scatter
:
plot_df.plot.scatter(x='height', y='width', s=10 * plot_df['count']**2,
c='count', cmap='viridis')
我想从 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 处。如何为该点指定代表 "Two occurences" 的颜色。 如果颜色是从连续光谱中自动选取的,就像在彩条图中那样,那就更好了。这样颜色阴影就已经给了你频率的印象,而不是通过手动查找颜色代表它。
另一种着色方法是将出现频率编码为圆点的半径。
编辑:
为了具体说明我的问题,我发现 df.groupby(['width','height']).size()
给出了所有组合的计数。
现在我缺乏 link 这些信息与图中点的颜色(或大小)的技能。
所以让我们把它变成真的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
散点图中的颜色和大小由 c
和 s
关键字控制,如果您使用 DataFrame.plot.scatter
:
plot_df.plot.scatter(x='height', y='width', s=10 * plot_df['count']**2,
c='count', cmap='viridis')