友情提示:380元/半年,儿童学编程,就上码丁实验室。
安装必要的模块
Windows用户安装四个模块:
-
python_dateutil
-
pyparsing
-
Numpy
-
matplotlib
安装Python模块参考下文:
Python遇上剪切板
模块的基本使用
from matplotlib import pyplot
import random
x = list(range(0,100))
y = [random.randint(0,100) for r in range(0,100)]
fig1 = pyplot.figure()#初始化一个空白画布
pyplot.plot(x, y, ‘-’)#生成一个折线图,X轴,Y轴,图形样式
pyplot.title(‘First Plot – Random integers’)
pyplot.xlabel(‘X Axis’)
pyplot.ylabel(‘Y Axis’)
pyplot.show()
生成的图片见下图:
生成的随机数折线图
结合CSV文件生成图形
CSV文件如下图:
csv 数据
该数据可以由Arduino生成,参考下文:
Python与arduino文件IO操作简介
该例子将生成两个图片,一个是折线图一个是柱状图,代码如下:
import csv
from matplotlib import pyplot
num = []
btnValues = []
potValues = []
with open(‘Arduino_data.csv’, ‘r’) as f:
reader = csv.reader(f)
header = next(reader, None)#读取第一行标题
for row in reader:
num.append(int(row[0]))#序列
potValues.append(float(row[1]))#电位计数据列
btnValues.append(int(row[2]))#按钮数据列
pyplot.subplot(2, 1, 1)##三个参数的意思是:整个图表分为2行1列,该子图表位于第一行
pyplot.plot(num, potValues, ‘-’)#生成折线图
pyplot.title(‘Line plot – ‘ + header[1])
pyplot.xlim([1, 30])
pyplot.xlabel(‘X Axis’)
pyplot.ylabel(‘Y Axis’)
pyplot.subplot(2, 1, 2)#三个参数的意思是:整个图表分为2行1列,该子图表位于第二行
pyplot.bar(num, btnValues)#生成柱状图
pyplot.title(‘Bar chart – ‘ + header[2])
pyplot.xlim([1, 30])#x轴坐标范围
pyplot.xlabel(‘X Axis’)
pyplot.ylabel(‘Y Axis’)
pyplot.tight_layout()#下面有比较
pyplot.show()
有pyplot.tight_layout()语句
无pyplot.tight_layout()语句
喜欢文章,欢迎大家转发!!!