python – 动态更新matplotlib中的条形图
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 动态更新matplotlib中的条形图,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2115字,纯文字阅读大概需要4分钟。
内容图文
![python – 动态更新matplotlib中的条形图](/upload/InfoBanner/zyjiaocheng/712/a9a7057102df42359f48c54e14df7cc6.jpg)
我的Raspberry Pi附带了许多传感器;我使用TCP每秒两次将数据发送到我的PC.我想使用matplotlib连续绘制这些值.
我目前使用的方法似乎效率低下(我正在清理子图并每次重绘它)并且有一些不良缺点(每次都会重新调整比例;我希望它保持在0.0 – 5.0之间).我知道有一种方法可以做到这一点,而不必清除和重绘,但似乎无法搞清楚.以下是我目前的代码:
import socket
import sys
import time
from matplotlib import pyplot as plt
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('192.168.0.10', 10000)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
# Initial setup for the bar plot
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
x = [1,2,3]
labels = ['FSR', 'Tilt', 'IR']
ax.set_xticklabels(labels)
y = [5.0,5.0,5.0]
ax.bar(x,y)
fig.autofmt_xdate()
plt.draw()
#Grab and continuously plot sensor values
try:
for i in range(300):
amount_received = 0
amount_expected = len("0.00,0.00,0.00")
# Receive data from RasPi
while amount_received < amount_expected:
data = sock.recv(14)
amount_received += len(data)
print >>sys.stderr, 'received "%s"' % data
# Plot received data
y = [float(datum) for datum in data.split(',')]
ax.clear()
ax.bar(x,y)
plt.draw()
time.sleep(0.5)
#Close the socket
finally:
print >>sys.stderr, 'closing socket'
sock.close()
解决方法:
你可以使用animation.FuncAnimation.
绘制一次条形图并保存返回值,这是一组Rects:
rects = plt.bar(range(N), x, align='center')
然后,要更改条形的高度,请调用rect.set_height:
for rect, h in zip(rects, x):
rect.set_height(h)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def animate(frameno):
x = mu + sigma * np.random.randn(N)
n, _ = np.histogram(x, bins, normed=True)
for rect, h in zip(patches, n):
rect.set_height(h)
return patches
N, mu, sigma = 10000, 100, 15
fig, ax = plt.subplots()
x = mu + sigma * np.random.randn(N)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
frames = 100
ani = animation.FuncAnimation(fig, animate, blit=True, interval=0,
frames=frames,
repeat=False)
plt.show()
内容总结
以上是互联网集市为您收集整理的python – 动态更新matplotlib中的条形图全部内容,希望文章能够帮你解决python – 动态更新matplotlib中的条形图所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。