我用matplotlib创建了一个关于水果的散点图。这是python算法。
#
# Creat a scatter plot about fruits!
#
import numpy
import matplotlib.pyplot
# read refined results from TXT file
lines = []
with open("fruits.tsv", "r") as dataFile:
lines = dataFile.readlines()
# remove line breaks
lines = [line.strip() for line in lines]
# break lines into tokens
tuples = [line.split("\t") for line in lines]
# remove the column names
titles = tuples.pop(0)
# make lists for each column
costs = [float(tuple[0]) for tuple in tuples]
calories = [int(tuple[1]) for tuple in tuples]
name = [tuple[2] for tuple in tuples]
plot = matplotlib.pyplot.scatter(costs, calories)
matplotlib.pyplot.title("Fruits by Cost and Calories")
matplotlib.pyplot.ylabel(titles[2])
matplotlib.pyplot.xlabel(titles[1])
matplotlib.pyplot.semilogy()
matplotlib.pyplot.grid(True, which='both')
matplotlib.pyplot.show()
这是我的tsv文件。
Cost Calories Name
2.1 5 Apple
1.4 4 Peach
4.1 2 Plum
3.6 1 Banana
(是的,数据有点古怪。) 当我明确输入y轴的成本时,为什么名字出现在y轴上?
要清楚,为什么输入成本时y轴上的名字?
答案 0 :(得分:2)
Python列表从0开始索引,而不是1:
>>> titles
['Cost', 'Calories', 'Name']
>>> titles[0]
'Cost'
>>> titles[1]
'Calories'
>>> titles[2]
'Name'
除了#1:
lines = []
不需要。删除它然后看 - 它只是创建一个空列表,它被丢弃在“with”中。
除了#2:很诱人,请不要把你的元组称为元组;破坏了内置类型。它们在转换方面非常方便(例如,你在这里使用了“float”和“int”。)