【问题标题】:CSV plotting in Python according to category/name根据类别/名称在 Python 中绘制 CSV
【发布时间】:2018-10-19 22:23:59
【问题描述】:

我已经设法根据某人为 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 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 查看第四列?我已将物种名称分开到它自己的列表中,但我认为它在这里对我没有任何用处。我知道如何绘制列,但不知道如何对行进行分类。

【问题讨论】:

    标签: python database csv matplotlib plot


    【解决方案1】:

    你只需要使用 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)
    

    当然,SPECIES_COLORS 字典可以在函数体之外定义。

    来源:scatter function documentation

    【讨论】:

    • 这完全有效!不过,我对逻辑有点迷失。它是如何“知道”哪些是哪些?例如,当我将数据分成不同的列表时,它是如何知道哪些点是 Iris-Setosa 的?它是内置的吗?
    • 它知道颜色,因为 colors 是为了保持坐标列表的相同顺序而构建的,在您的示例中,将使用以下值调用 scatter 函数: plt.scatter([3.5, 3.2,2.7],[5.1,7.0,5.8],c=["b","y","r"])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2014-09-08
    相关资源
    最近更新 更多