根据类别/名称在Python中绘制CSV
我已经根据某人输入的x轴和y轴的列号绘制了数据。我的数据格式为CSV,其中第五列中有物种名称: 5.1,3.5,1.4,0.2,刚毛鸢尾 7.0,3.2,4.7,1.4,虹膜花色 5.8,2.7,5.1,1.9,弗吉尼亚鸢尾 目前,我的程序运行正常,并在需要的地方绘制点。问题是这些点的颜色都是一样的。我需要以某种方式告诉程序查看物种名称,并使用它们作为相应值的类别。有三种物种,因此数据应为三种颜色,并带有图例根据类别/名称在Python中绘制CSV,python,database,csv,matplotlib,plot,Python,Database,Csv,Matplotlib,Plot,我已经根据某人输入的x轴和y轴的列号绘制了数据。我的数据格式为CSV,其中第五列中有物种名称: 5.1,3.5,1.4,0.2,刚毛鸢尾 7.0,3.2,4.7,1.4,虹膜花色 5.8,2.7,5.1,1.9,弗吉尼亚鸢尾 目前,我的程序运行正常,并在需要的地方绘制点。问题是这些点的颜色都是一样的。我需要以某种方式告诉程序查看物种名称,并使用它们作为相应值的类别。有三种物种,因此数据应为三种颜色,并带有图例 import random import matplotlib.pyplot as p
import random
import matplotlib.pyplot as plt
import csv
#a function that will take data from a CSV and plot them according to which columns are inputted
def plot_data(fileName,colX,colY):
dataList = []
sepalLengthCM = []
sepalWidthCM= []
petalLengthCM =[]
petalWidthCM = []
species = []
#reading the file
with open(fileName, "r") as file:
data = csv.reader(file)
#making a list of all the rows of data
for row in data:
dataList.append(row)
#seperating each column into it's own list so I can plot them against eachother. For example, I'm plotting row 2 as the x axis and row 1 as the y
for row in range(0, len(dataList)-1):
sepalLengthCM.append(dataList[row][0])
sepalWidthCM.append(dataList[row][1])
petalLengthCM.append(dataList[row][2])
petalWidthCM.append(dataList[row][3])
species.append(dataList[row][4])
#placing each column into a list of 'options' that the user can choose from.
optionsList = [sepalLengthCM, sepalWidthCM, petalLengthCM, petalWidthCM]
#using the indexes of the options list to plot the scatter plot. It works, but without distinction among species
plt.scatter(optionsList[colX],optionsList[colY])
plt.show()
plot_data("iris.csv",2,1)
我如何告诉python查看第四列?我已经把这个物种的名字分门别类,但我不认为它对我有任何用处。我知道如何绘制列,但我不知道如何对行进行分类。您只需要使用scatter函数的c参数,下面是一个示例
SPECIES_COLORS = {
"Iris-setosa": "b",
"Iris-versicolor": "y",
"Iris-virginica": "r",
}
colors = [SPECIES_COLORS[s] for s in species]
plt.scatter(optionsList[colX],optionsList[colY],c=colors)
当然,可以在函数体之外定义种类颜色词典
来源:这完全奏效了!不过,我对逻辑有点迷茫。它怎么知道是哪一个?例如,当我将数据分成不同的列表时,它如何知道哪些点是Iris Setosa?它是内置的吗?它知道颜色,因为颜色是为了保持坐标列表的相同顺序而构建的,在您的示例中,散射函数将使用以下值调用:plt.scatter[3.5,3.2,2.7],[5.1,7.0,5.8],c=[b,y,r]