Skip to content

Instantly share code, notes, and snippets.

@dpkoch
Created March 21, 2017 22:58
Show Gist options
  • Save dpkoch/d8b1ce1d363f931405d7da98125231ca to your computer and use it in GitHub Desktop.
Save dpkoch/d8b1ce1d363f931405d7da98125231ca to your computer and use it in GitHub Desktop.
Script for plotting rosbag topics. Depends on pybag.
#!/usr/bin/env python
import sys
import pybag
import matplotlib.pyplot as plt
def initialize_plot(num_fields):
config = {}
config['fig'] = plt.figure()
config['num_fields'] = num_fields
return config
def add_plot(config, index, time, data, name):
plt.subplot(config['num_fields'], 1, index+1)
if type(data[0]) is tuple:
pass
else:
plt.plot(time, data)
plt.title(name)
def finalize_plot(config):
plt.show(block=False)
def dig(obj, name, time):
# if obj is a list of scalars or tuples, plot
if type(obj) is list:
if type(obj[0]) is tuple:
print 'Plotting tuple %s' % (name)
size = len(obj[0])
config = initialize_plot(size)
for i in xrange(size):
add_plot(config, i, time, [obj[t][i] for t in xrange(len(obj))], "%s[%d]" % (name, i))
finalize_plot(config)
elif isinstance(obj[0], (int,float)):
print 'Plotting scalar %s' % (name)
config = initialize_plot(1)
add_plot(config, 0, time, obj, name)
finalize_plot(config)
# if obj is a dict, dig deeper
elif type(obj) is dict:
# if there's only one, recurse in
if len(obj.keys()) is 1:
dig(obj[obj.keys()[0]], name + '.' + obj.keys()[0], time)
return
# if all keys map to lists of scalars, plot them in subplots
scalars = True
for k,v in obj.iteritems():
if not (type(v) is list and isinstance(v[0], (int,float))):
scalars = False
break
if scalars:
config = initialize_plot(len(obj.keys()))
for k,v in obj.iteritems():
print 'Plotting %s' % (name + '.' + k)
for i,k in enumerate(obj.keys()):
add_plot(config, i, time, obj[k], name + '.' + k)
finalize_plot(config)
return
# otherwise keep digging
print 'Select a field:'
for index, key in enumerate(obj.keys()):
print '\t%2d: %s' % (index, key)
valid = False
while not valid:
selection = input('Enter index: ')
valid = selection in xrange(len(obj.keys()))
dig(obj[obj.keys()[selection]], name + '.' + obj.keys()[selection], time)
else:
print 'Error: unsupported type %s' % (type(obj))
bag_file = sys.argv[1]
print 'Loading bag file...'
bag = pybag.PyBag(bag_file)
data = bag.data()
print 'Done.'
topics = bag.topics()
start_time = bag.start_time()
done = False
while not done:
print '=' * 60
print 'Select a topic:'
for index, topic in enumerate(topics):
print '\t%2d: %s' % (index, topic)
valid = False
while not valid:
selection = input('Enter index or -1 to quit: ')
if selection == -1:
sys.exit()
valid = selection in xrange(len(topics))
name = topics[selection]
current = data[bag.topic_to_field(topics[selection])]
dig(current, name, current['__time__'])
@krixkrix
Copy link

Where do I find pybag?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment