CSV代表“逗号分隔值”。这意味着CSV文件中的数据(值)由分隔符分隔,即,逗号CSV文件中的数据以扩展名为. csv的表格格式存储。通常,CSV文件与Microsoft Excel工作表一起使用。CSV文件包含许多记录,数据分布在各行和各列中。在本文中,我们将在Python中可视化CSV文件中的数据。
要提取CSV文件中的数据,必须在我们的程序中导入CSV模块,如下所示:
import csv
with open('file.csv') as File:
Line_reader = csv.reader(File)
例1:可视化条形图
以下CSV文件包含保存为“biostats. csv”的不同人员姓名、性别和年龄:
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('biostats.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter = ',')
for row in plots:
x.append(row[0])
y.append(int(row[2]))
plt.bar(x, y, color = 'g', width = 0.72, label = "Age")
plt.xlabel('Names')
plt.ylabel('Ages')
plt.title('Ages of different persons')
plt.legend()
plt.show()
输出
例2:可视化折线图
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('Weatherdata.csv','r') as csvfile:
lines = csv.reader(csvfile, delimiter=',')
for row in lines:
x.append(row[0])
y.append(int(row[1]))
plt.plot(x, y, color = 'g', linestyle = 'dashed',
marker = 'o',label = "Weather Data")
plt.xticks(rotation = 25)
plt.xlabel('Dates')
plt.ylabel('Temperature(°C)')
plt.title('Weather Report', fontsize = 20)
plt.grid()
plt.legend()
plt.show()
输出
例3:可视化散点图
import matplotlib.pyplot as plt
import csv
Names = []
Values = []
with open('bldprs_measure.csv','r') as csvfile:
lines = csv.reader(csvfile, delimiter=',')
for row in lines:
Names.append(row[0])
Values.append(int(row[1]))
plt.scatter(Names, Values, color = 'g',s = 100)
plt.xticks(rotation = 25)
plt.xlabel('Names')
plt.ylabel('Values')
plt.title('Patients Blood Pressure Report', fontsize = 20)
plt.show()
输出
例4:可视化饼图
import matplotlib.pyplot as plt
import csv
Subjects = []
Scores = []
with open('SubjectMarks.csv', 'r') as csvfile:
lines = csv.reader(csvfile, delimiter = ',')
for row in lines:
Subjects.append(row[0])
Scores.append(int(row[1]))
plt.pie(Scores,labels = Subjects,autopct = '%.2f%%')
plt.title('Marks of a Student', fontsize = 20)
plt.show()
输出