-
Notifications
You must be signed in to change notification settings - Fork 6
Use PyQtGraph to plot data #94
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Giulero
wants to merge
10
commits into
main
Choose a base branch
from
add_pyqtgraph_plotting
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
ebf42ea
Add PyQtGraphViewerCanvas
Giulero ef4716b
Add __call__ method to ColorPalette to make it compliant with the pyq…
Giulero 56d65e3
Replace pg.intColor with ColorPalette instance in PyQtGraphViewerCanvas
Giulero 782397b
Add some documentation
Giulero aa74bc7
Add space bar functionality to toggle play/pause in RobotViewerMainWi…
Giulero f3ad8ef
Format with black
Giulero d3ef505
Add pyqtgraph to install_requires in setup.cfg
Giulero 1772740
Replace MatplotlibViewerCanvas with PyQtGraphViewerCanvas in PlotItem
Giulero 1306f38
Update robot_log_visualizer/ui/gui.py
Giulero afc930b
Merge branch 'main' into add_pyqtgraph_plotting
GiulioRomualdi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
168 changes: 168 additions & 0 deletions
168
robot_log_visualizer/plotter/pyqtgraph_viewer_canvas.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,168 @@ | ||
from PyQt5 import QtWidgets, QtCore | ||
import pyqtgraph as pg | ||
import numpy as np | ||
from robot_log_visualizer.plotter.color_palette import ColorPalette | ||
|
||
class PyQtGraphViewerCanvas(QtWidgets.QWidget): | ||
def __init__(self, parent, signal_provider, period): | ||
""" | ||
Initialize the PyQtGraphViewerCanvas. | ||
Parameters: | ||
parent (QWidget): The parent widget. | ||
signal_provider (SignalProvider): The signal provider for data. | ||
period (float): The update period in seconds. | ||
""" | ||
super().__init__(parent) | ||
|
||
self.signal_provider = signal_provider | ||
self.period_in_ms = int(period * 1000) | ||
|
||
self.active_paths = {} # Plotted curves | ||
self.annotations = [] # Text annotations | ||
|
||
self.layout = QtWidgets.QVBoxLayout(self) | ||
self.plot_widget = pg.PlotWidget() | ||
self.plot_widget.setBackground("w") | ||
self.layout.addWidget(self.plot_widget) | ||
|
||
# Set minimalistic axis labels | ||
label_style = {"color": "#000000", "font-size": "12pt", "font-weight": "normal"} | ||
self.plot_widget.setLabel("bottom", "Time [s]", **label_style) | ||
self.plot_widget.setLabel("left", "Value", **label_style) | ||
|
||
self.plot_widget.showGrid(x=True, y=True) | ||
|
||
self.plot_widget.addLegend( | ||
offset=(10, 10), labelTextSize="12pt", brush=(255, 255, 255, 150) | ||
) | ||
self.plot_widget.plotItem.legend.setParentItem(self.plot_widget.plotItem) | ||
self.plot_widget.plotItem.legend.anchor((0.0, 0), (0.0, 0)) | ||
|
||
# Vertical line for animation (soft gray) | ||
self.vertical_line = pg.InfiniteLine( | ||
angle=90, movable=False, pen=pg.mkPen(color="#555555", width=1) | ||
) | ||
self.plot_widget.addItem(self.vertical_line) | ||
|
||
# Timer for updating the vertical line | ||
self.timer = QtCore.QTimer() | ||
self.timer.timeout.connect(self.update_vertical_line) | ||
self.timer.start(self.period_in_ms) | ||
|
||
# Color palette | ||
self.color_palette = ColorPalette() | ||
|
||
# Interaction | ||
self.plot_widget.scene().sigMouseClicked.connect(self.on_click) | ||
|
||
def update_plots(self, paths, legends): | ||
""" | ||
Update plots based on provided data paths and their corresponding legends. | ||
|
||
Parameters: | ||
paths (list): List of paths representing data series to plot. | ||
legends (list): Corresponding legend labels for the paths. | ||
""" | ||
for path, legend in zip(paths, legends): | ||
path_string = "/".join(path) | ||
legend_string = "/".join(legend[1:]) | ||
|
||
if path_string not in self.active_paths: | ||
data = self.signal_provider.data | ||
for key in path[:-1]: | ||
data = data[key] | ||
try: | ||
datapoints = data["data"][:, int(path[-1])] | ||
except IndexError: | ||
datapoints = data["data"][:] | ||
|
||
timestamps = data["timestamps"] - self.signal_provider.initial_time | ||
color = self.color_palette(len(self.active_paths)) | ||
curve = self.plot_widget.plot( | ||
timestamps, | ||
datapoints, | ||
pen=pg.mkPen(color=color, width=2), | ||
name=legend_string, | ||
symbol=None, | ||
) | ||
self.active_paths[path_string] = curve | ||
active_path_strings = {"/".join(path) for path in paths} | ||
paths_to_remove = [p for p in self.active_paths if p not in active_path_strings] | ||
for path in paths_to_remove: | ||
self.plot_widget.removeItem(self.active_paths[path]) | ||
del self.active_paths[path] | ||
|
||
# Set the x-axis range to the full time range of the data | ||
self.plot_widget.setXRange( | ||
0, self.signal_provider.end_time - self.signal_provider.initial_time | ||
) | ||
|
||
def update_vertical_line(self): | ||
""" | ||
Update the position of the vertical line based on the current time. | ||
""" | ||
current_time = self.signal_provider.current_time | ||
self.vertical_line.setValue(current_time) | ||
|
||
def on_click(self, event): | ||
""" | ||
Handle mouse click events to add annotations to the plot. | ||
Clicking on a data point will display its coordinates. | ||
""" | ||
pos = event.scenePos() | ||
if self.plot_widget.sceneBoundingRect().contains(pos): | ||
# Convert scene coordinates to plot coordinates | ||
mouse_point = self.plot_widget.plotItem.vb.mapSceneToView(pos) | ||
x_click, y_click = mouse_point.x(), mouse_point.y() | ||
|
||
closest_curve, closest_point, min_dist = None, None, float("inf") | ||
|
||
for curve in self.active_paths.values(): | ||
xdata, ydata = curve.getData() | ||
distances = np.sqrt((xdata - x_click) ** 2 + (ydata - y_click) ** 2) | ||
index = np.argmin(distances) | ||
distance = distances[index] | ||
if distance < min_dist: | ||
min_dist = distance | ||
closest_curve = curve | ||
closest_point = (xdata[index], ydata[index]) | ||
|
||
# If the closest point is within a certain distance, add an annotation | ||
if min_dist < 0.01 * ( | ||
self.plot_widget.viewRange()[0][1] - self.plot_widget.viewRange()[0][0] | ||
): | ||
text = f"{closest_point[0]:.3f}, {closest_point[1]:.3f}" | ||
annotation = pg.TextItem( | ||
text, | ||
anchor=(0, 1), | ||
color="#000000" | ||
) | ||
annotation.setPos(*closest_point) | ||
self.plot_widget.addItem(annotation) | ||
self.annotations.append(annotation) | ||
|
||
def clear_annotations(self): | ||
""" | ||
Clear all annotations from the plot. | ||
""" | ||
for annotation in self.annotations: | ||
self.plot_widget.removeItem(annotation) | ||
self.annotations.clear() | ||
|
||
def quit_animation(self): | ||
""" | ||
Stop the animation and clear all plots. | ||
""" | ||
self.timer.stop() | ||
|
||
def pause_animation(self): | ||
""" | ||
Pause the animation by stopping the timer. | ||
""" | ||
self.timer.stop() | ||
|
||
def resume_animation(self): | ||
""" | ||
Resume the animation by restarting the timer. | ||
""" | ||
self.timer.start(self.period_in_ms) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] Consider extracting the magic number 0.01 into a named constant to improve code readability and maintainability.
Copilot uses AI. Check for mistakes.