如何使用python根据坐标平面的区域更改点的颜色?

分享于2022年07月17日 matplotlib pandas python 问答
【问题标题】:如何使用python根据坐标平面的区域更改点的颜色?(How can I change the colors of the points based on the areas of the coordinate plane using python?)
【发布时间】:2022-01-27 12:08:18
【问题描述】:

我是 python 编程的新手,我想根据坐标平面区域(∞,∞)-->绿色(-∞,∞)-->黄色等更改图表中点的颜色。数据必须来自 csv 文件。我尝试了一些 if-else 条件,但无法做到。这里是来自 csv 的数据

 X,Y
 1,3
-8,-8
 8,8
 8,-4
-8,-7
-14,-13
-8,-7
-16,-16

这里是我的代码,我用数组尝试了一些荒谬的事情,对此感到抱歉

from matplotlib import pyplot as plt
import math
import csv
import pandas as pd


path2Csv="sonuçlar.csv"
with open(path2Csv,newline='\n') as g:
   reader=csv.reader(g)
   dataResult=list(reader)[1:] 

col_list=["X","Y"]
df = pd.read_csv(path2Csv, usecols=col_list)
xleft=[0]*len(dataResult)   
xright=[0]*len(dataResult)
yup=[0]*len(dataResult)
ydown=[0]*len(dataResult)
eu1=df["X"]
eu2=df["Y"]
for i in range(len(dataResult)):
   if eu1[i]<0:
      xleft[i]=eu1[i]
   if eu1[i]>0:
      xright[i]=eu1[i]
   if eu2[i]<0:
      ydown[i]=eu2[i]
   if eu2[i]>0:
      yup[i]=eu2[i]

plt.scatter(xleft,yup,c="yellow")
plt.scatter(xleft,ydown,c="blue")
plt.scatter(xright,yup,c="gray")
plt.scatter(xright,ydown,c="green")#should i create new arrays from df["X"] and df["Y"] or 
                                   #use something else instead of scatter?
plt.show()

如果你能给我一些提示那就太好了

  • 我现在找到了一种方法,但我仍然愿意接受您的建议,谢谢!

【解决方案1】:

改变点颜色的主要思路是

  • 通过 x y 计算颜色
  • 将颜色保存到列表中
  • 调用 plt.scatter 计算颜色列表

我写了一个demo来绘制如下的颜色表。

使用 HSV 绘制渐变色更容易:)

How can I change the colors of the points based on the areas of the coordinate plane using python?

import matplotlib.colors
import matplotlib.pyplot as plt

xList = []
yList = []
colors = []
count = 50
for x in range(0, count):
    for y in range(0, count):
        xList.append(x)
        yList.append(y)
        hue = x / count
        saturation = (count - y) / count
        colors.append(matplotlib.colors.hsv_to_rgb([hue, saturation, 1]))

plt.scatter(xList, yList, c=colors)
plt.show()