首页 > 解决方案 > 取决于索引号的熊猫数据框的不同颜色

问题描述

我有一个 500 行的 pandas 数据框,其中有 2 列 x 和 y 指的是表中的坐标。但是我希望能够为从 0 到 249 的点分配不同的颜色,然后是 250 到 499,例如一半是红色,一半是蓝色。我该怎么做?

500 行 2 列的表格

编码:

diagram = pos_table.plot.scatter('x', 'y', c = 'turquoise', s = 4)

结果:

代码输出

标签: pythonpandasmatplotlibscatter-plot

解决方案


选择第一行和最后250一行DataFrame.iloc,然后传递ax给第二行plot

length = len(pos_table)
half = length //
ax = pos_table.iloc[:250].plot.scatter('x', 'y', c = 'red', s = 4)
pos_table.iloc[250:].plot.scatter('x', 'y', c = 'blue', s = 4, ax=ax)

或动态计数值:

length = len(pos_table)
half = length // 2
ax = pos_table.iloc[:half].plot.scatter('x', 'y', c = 'red', s = 4)
pos_table.iloc[half:].plot.scatter('x', 'y', c = 'blue', s = 4, ax=ax)

示例:(更改s以便更好地查看)

pos_table = pd.DataFrame({'x':[2,3,4,6,2,4,6,8,5,7],
                          'y':[4,3,1,4,6,8,5,3,5,4]})

length = len(pos_table)
half = length // 2
ax = pos_table.iloc[:half].plot.scatter('x', 'y', c = 'red', s = 90)
pos_table.iloc[half:].plot.scatter('x', 'y', c = 'blue', s = 90, ax=ax)

图形


推荐阅读