python - pandas Dataframe 的不同颜色取决于索引号

标签 python pandas matplotlib scatter-plot

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

The table of 500 rows, 2 columns

代码:

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

结果:

The code output

最佳答案

DataFrame.iloc 选择第一个和最后一个 250 行然后将 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)

graph

关于python - pandas Dataframe 的不同颜色取决于索引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59696883/

相关文章:

python - Pandas Python - 将列表列表列转换为多列

python - Matplotlib 导航工具栏 : remove "Edit curves lines and axes parameters"

python - 为什么 python 脚本抛出 AttributeError : 'module' object not found, 但在可执行文件时有效?

python - 如何替换 pandas 数据框中列中的日期?

python - 为什么 pandas strftime 会引发 FutureWarning 以及如何避免它?

python - 当两列相似时替换它们

python - NameError : name 'defaultParams' is not defined while running the . exe 使用 Pyinstaller 转换

python - 从 pandas 数据框绘制和格式化 seaborn 图表

python - 如何检查字典中的键是否以另一个字典中的键开头?

python - 如何检索列表中的 n 项组