matplotlib读取csv文件

一,从本地加载csv文件

from matplotlib import pyplot as plt
import numpy as np
import csv
#用来正常显示中文标签
plt.rcParams['font.sans-serif']=['SimHei']
#用来正常显示负号
plt.rcParams['axes.unicode_minus']=False

#定义两个空列表存放x,y轴数据点
x=[]
y=[]
with open("csv//matplotlib-demo.csv",'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        x.append(int(row[0]))  #从csv读取的数据是str类型
#         print("x:",x)
        y.append(int(row[1]))
#         print("y:",y)
#画折线图
plt.plot(x,y,label='模拟数据')
plt.xlabel('x')
plt.ylabel('y')
plt.title('演示从文件加载数据')
plt.legend()
plt.show()

结果显示:
这里写图片描述
二,加载网络接口数据

import json #解析json数据
import urllib  # 利用urllib.request网络存取数据

#利用urllib加载接口数据
url = 'https://api.douban.com/v2/book/1220562'
source_code = urllib.request.urlopen(url).read().decode()
source_code
#通过json.loads()方式将json格式的字符串转换为python中的字典数据类型
data = json.loads(source_code)
# type(data)  #dict

#通过data[‘tags’]获取该键所对应的值
tags = data['tags']
tags
打印结果:
[{'count': 144, 'name': '片山恭一', 'title': '片山恭一'},
 {'count': 70, 'name': '日本', 'title': '日本'},
 {'count': 65, 'name': '日本文学', 'title': '日本文学'},
 {'count': 40, 'name': '小说', 'title': '小说'},
 {'count': 33, 'name': '满月之夜白鲸现', 'title': '满月之夜白鲸现'},
 {'count': 17, 'name': '爱情', 'title': '爱情'},
 {'count': 10, 'name': '純愛', 'title': '純愛'},
 {'count': 9, 'name': '外国文学', 'title': '外国文学'}]

plt.figure(figsize=(10,6))

x = []  #存放x轴数据
y = []
#遍历tags,取到count作为y轴,name作为x轴
for tag in tags:
    x.append(tag["name"])
    y.append(tag["count"])
plt.bar(x,y,label="图书搜索热词")
plt.title("图书热词搜索排名")
plt.legend()
plt.xlabel('x轴-搜索热词')
plt.ylabel('y轴-搜索热词排名')
plt.show()


三,用numpy加载csv数据

x,y = np.loadtxt("csv//matplotlib-demo.csv",delimiter=',',unpack=True)
print("x值:",x,"y值:",y)
打印结果:
x值: [ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]
y值: [5. 3. 4. 7. 4. 3. 5. 7. 4. 4.]

#画折线图
plt.plot(x,y,label='模拟数据')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('Numpy简化数据加载过程')
plt.legend()
plt.show()

 
---------------------
作者:pennyyangpei
来源:CSDN
原文:https://blog.csdn.net/qq_42379006/article/details/80834096
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/3daytears/p/9988242.html