| 1 |
"""Enhanced wxPython Plotting Library. |
| 2 |
|
| 3 |
----------------------------------------------------------------------------- |
| 4 |
Name: wx.lib.plot.py |
| 5 |
Purpose: Line, Bar and Scatter Graphs |
| 6 |
Author: Gordon Williams |
| 7 |
Created: 2003/11/03 |
| 8 |
RCS-ID: $Id: plot.py 65712 2010-10-01 17:56:32Z RD $ |
| 9 |
Copyright: (c) 2002 |
| 10 |
Licence: Use as you wish. |
| 11 |
----------------------------------------------------------------------------- |
| 12 |
12/15/2003 - Jeff Grimmett ([email protected]) |
| 13 |
o 2.5 compatability update. |
| 14 |
o Renamed to plot.py in the wx.lib directory. |
| 15 |
o Reworked test frame to work with wx demo framework. This saves a bit |
| 16 |
of tedious cut and paste, and the test app is excellent. |
| 17 |
12/18/2003 - Jeff Grimmett ([email protected]) |
| 18 |
o wxScrolledMessageDialog -> ScrolledMessageDialog |
| 19 |
Oct 6, 2004 Gordon Williams ([email protected]) |
| 20 |
- Added bar graph demo |
| 21 |
- Modified line end shape from round to square. |
| 22 |
- Removed FloatDCWrapper for conversion to ints and ints in arguments |
| 23 |
Oct 15, 2004 Gordon Williams ([email protected]) |
| 24 |
- Imported modules given leading underscore to name. |
| 25 |
- Added Cursor Line Tracking and User Point Labels. |
| 26 |
- Demo for Cursor Line Tracking and Point Labels. |
| 27 |
- Size of plot preview frame adjusted to show page better. |
| 28 |
- Added helper functions PositionUserToScreen and PositionScreenToUser in |
| 29 |
PlotCanvas. |
| 30 |
- Added functions GetClosestPoints (all curves) and GetClosestPoint (only |
| 31 |
closest curve) can be in either user coords or screen coords. |
| 32 |
Jun 22, 2009 Florian Hoech ([email protected]) |
| 33 |
- Fixed exception when drawing empty plots on Mac OS X |
| 34 |
- Fixed exception when trying to draw point labels on Mac OS X (Mac OS X |
| 35 |
point label drawing code is still slow and only supports wx.COPY) |
| 36 |
- Moved label positions away from axis lines a bit |
| 37 |
- Added PolySpline class and modified demo 1 and 2 to use it |
| 38 |
- Added center and diagonal lines option (Set/GetEnableCenterLines, |
| 39 |
Set/GetEnableDiagonals) |
| 40 |
- Added anti-aliasing option with optional high-resolution mode |
| 41 |
(Set/GetEnableAntiAliasing, Set/GetEnableHiRes) and demo |
| 42 |
- Added option to specify exact number of tick marks to use for each axis |
| 43 |
(SetXSpec(<number>, SetYSpec(<number>) -- work like 'min', but with |
| 44 |
<number> tick marks) |
| 45 |
- Added support for background and foreground colours (enabled via |
| 46 |
SetBackgroundColour/SetForegroundColour on a PlotCanvas instance) |
| 47 |
- Changed PlotCanvas printing initialization from occurring in __init__ to |
| 48 |
occur on access. This will postpone any IPP and / or CUPS warnings |
| 49 |
which appear on stderr on some Linux systems until printing functionality |
| 50 |
is actually used. |
| 51 |
|
| 52 |
This is a simple light weight plotting module that can be used with |
| 53 |
Boa or easily integrated into your own wxPython application. The |
| 54 |
emphasis is on small size and fast plotting for large data sets. It |
| 55 |
has a reasonable number of features to do line and scatter graphs |
| 56 |
easily as well as simple bar graphs. It is not as sophisticated or |
| 57 |
as powerful as SciPy Plt or Chaco. Both of these are great packages |
| 58 |
but consume huge amounts of computer resources for simple plots. |
| 59 |
They can be found at http://scipy.com |
| 60 |
|
| 61 |
This file contains two parts; first the re-usable library stuff, then, |
| 62 |
after a "if __name__=='__main__'" test, a simple frame and a few default |
| 63 |
plots for examples and testing. |
| 64 |
|
| 65 |
Based on wxPlotCanvas |
| 66 |
Written by K.Hinsen, R. Srinivasan; |
| 67 |
Ported to wxPython Harm van der Heijden, feb 1999 |
| 68 |
|
| 69 |
Major Additions Gordon Williams Feb. 2003 ([email protected]) |
| 70 |
-More style options |
| 71 |
-Zooming using mouse "rubber band" |
| 72 |
-Scroll left, right |
| 73 |
-Grid(graticule) |
| 74 |
-Printing, preview, and page set up (margins) |
| 75 |
-Axis and title labels |
| 76 |
-Cursor xy axis values |
| 77 |
-Doc strings and lots of comments |
| 78 |
-Optimizations for large number of points |
| 79 |
-Legends |
| 80 |
|
| 81 |
Did a lot of work here to speed markers up. Only a factor of 4 |
| 82 |
improvement though. Lines are much faster than markers, especially |
| 83 |
filled markers. Stay away from circles and triangles unless you |
| 84 |
only have a few thousand points. |
| 85 |
|
| 86 |
Times for 25,000 points |
| 87 |
Line - 0.078 sec |
| 88 |
Markers |
| 89 |
Square - 0.22 sec |
| 90 |
dot - 0.10 |
| 91 |
circle - 0.87 |
| 92 |
cross,plus - 0.28 |
| 93 |
triangle, triangle_down - 0.90 |
| 94 |
|
| 95 |
Thanks to Chris Barker for getting this version working on Linux. |
| 96 |
|
| 97 |
Zooming controls with mouse (when enabled): |
| 98 |
Left mouse drag - Zoom box. |
| 99 |
Left mouse double click - reset zoom. |
| 100 |
Right mouse click - zoom out centred on click location. |
| 101 |
""" |
| 102 |
|
| 103 |
from __future__ import annotations |
| 104 |
|
| 105 |
import contextlib |
| 106 |
import functools |
| 107 |
import string as _string |
| 108 |
import sys |
| 109 |
from typing import ClassVar, TYPE_CHECKING |
| 110 |
|
| 111 |
if TYPE_CHECKING: |
| 112 |
if sys.version_info >= (3, 11): |
| 113 |
from typing import Self |
| 114 |
else: |
| 115 |
from typing_extensions import Self |
| 116 |
|
| 117 |
|
| 118 |
import numpy as np |
| 119 |
import wx |
| 120 |
|
| 121 |
from DisplayCAL.wx_fixes import get_dc_font_scale |
| 122 |
|
| 123 |
|
| 124 |
def convert_to_list_of_tuples(iterable): |
| 125 |
"""Convert an iterable of iterables to a list of tuples.""" |
| 126 |
return [tuple(map(int, p)) for p in iterable] |
| 127 |
|
| 128 |
|
| 129 |
# ---------------------------------------------------------------------- |
| 130 |
# From wxPython Phoenix wx/lib/plot/utils.py with __nonzer__ fix |
| 131 |
# and Python 2.6 compatibility |
| 132 |
|
| 133 |
|
| 134 |
class DisplaySide: |
| 135 |
"""Generic class for describing which sides of a box are displayed. |
| 136 |
|
| 137 |
Used for fine-tuning the axis, ticks, and values of a graph. |
| 138 |
|
| 139 |
This class somewhat mimics a collections.namedtuple factory function in |
| 140 |
that it is an iterable and can have individual elements accessible by name. |
| 141 |
It differs from a namedtuple in a few ways: |
| 142 |
|
| 143 |
- it's mutable |
| 144 |
- it's not a factory function but a full-fledged class |
| 145 |
- it contains type checking, only allowing boolean values |
| 146 |
- it contains name checking, only allowing valid_names as attributes |
| 147 |
|
| 148 |
Args: |
| 149 |
bottom (bool): Display the bottom side. |
| 150 |
left (bool): Display the left side. |
| 151 |
top (bool): Display the top side. |
| 152 |
right (bool): Display the right side. |
| 153 |
""" |
| 154 |
|
| 155 |
# TODO: Do I want to replace with __slots__? |
| 156 |
# Not much memory gain because this class is only called a small |
| 157 |
# number of times, but it would remove the need for part of |
| 158 |
# __setattr__... |
| 159 |
valid_names = ("bottom", "left", "right", "top") |
| 160 |
|
| 161 |
def __init__(self, bottom, left, top, right): |
| 162 |
if not all(isinstance(x, bool) for x in [bottom, left, top, right]): |
| 163 |
raise TypeError("All args must be bools") |
| 164 |
self.bottom = bottom |
| 165 |
self.left = left |
| 166 |
self.top = top |
| 167 |
self.right = right |
| 168 |
|
| 169 |
def __str__(self) -> str: |
| 170 |
"""Return a string representation of the object. |
| 171 |
|
| 172 |
Returns: |
| 173 |
str: The string representation of the object. |
| 174 |
""" |
| 175 |
return ( |
| 176 |
f"{self.__class__.__name__}(bottom={self.bottom}, " |
| 177 |
f"left={self.left}, top={self.top}, right={self.right})" |
| 178 |
) |
| 179 |
|
| 180 |
def __repr__(self) -> str: |
| 181 |
"""Return a string representation of the object. |
| 182 |
|
| 183 |
Returns: |
| 184 |
str: The string representation of the object. |
| 185 |
""" |
| 186 |
# for now, just return the str representation |
| 187 |
return self.__str__() |
| 188 |
|
| 189 |
def __setattr__(self, name: str, value: bool) -> None: |
| 190 |
"""Override __setattr__ for type and name validation. |
| 191 |
|
| 192 |
Args: |
| 193 |
name (str): The name of the attribute to set. |
| 194 |
value (bool): The value to set the attribute to. |
| 195 |
|
| 196 |
Raises: |
| 197 |
NameError: If the name is not in valid_names. |
| 198 |
TypeError: If the value is not a boolean. |
| 199 |
""" |
| 200 |
if name not in self.valid_names: |
| 201 |
err_str = "attribute must be one of {}" |
| 202 |
raise NameError(err_str.format(self.valid_names)) |
| 203 |
if not isinstance(value, bool): |
| 204 |
raise TypeError(f"'{name}' must be a boolean") |
| 205 |
self.__dict__[name] = value |
| 206 |
|
| 207 |
def __len__(self) -> int: |
| 208 |
"""Return the number of sides. |
| 209 |
|
| 210 |
Returns: |
| 211 |
int: The number of sides (always 4). |
| 212 |
""" |
| 213 |
return 4 |
| 214 |
|
| 215 |
def __hash__(self) -> int: |
| 216 |
"""Return a hash of the object. |
| 217 |
|
| 218 |
Returns: |
| 219 |
int: The hash of the object. |
| 220 |
""" |
| 221 |
return hash(tuple(self)) |
| 222 |
|
| 223 |
def __getitem__(self, key: int) -> bool: |
| 224 |
"""Return the value of the specified side. |
| 225 |
|
| 226 |
Args: |
| 227 |
key (int): The index of the side to get (0: bottom, 1: left, 2: top, |
| 228 |
3: right). |
| 229 |
|
| 230 |
Returns: |
| 231 |
bool: The value of the specified side. |
| 232 |
""" |
| 233 |
return (self.bottom, self.left, self.top, self.right)[key] |
| 234 |
|
| 235 |
def __setitem__(self, key: int, value: bool) -> None: |
| 236 |
"""Set the value of the specified side. |
| 237 |
|
| 238 |
Args: |
| 239 |
key (int): The index of the side to set (0: bottom, 1: left, 2: top, |
| 240 |
3: right). |
| 241 |
value (bool): The value to set the side to. |
| 242 |
|
| 243 |
Raises: |
| 244 |
IndexError: If the key is out of range (not 0-3). |
| 245 |
""" |
| 246 |
if key == 0: |
| 247 |
self.bottom = value |
| 248 |
elif key == 1: |
| 249 |
self.left = value |
| 250 |
elif key == 2: |
| 251 |
self.top = value |
| 252 |
elif key == 3: |
| 253 |
self.right = value |
| 254 |
else: |
| 255 |
raise IndexError("list index out of range") |
| 256 |
|
| 257 |
def __iter__(self): |
| 258 |
"""Iterate over the sides of the box.""" |
| 259 |
return iter([self.bottom, self.left, self.top, self.right]) |
| 260 |
|
| 261 |
def __bool__(self): |
| 262 |
"""Return True if any of the sides are displayed.""" |
| 263 |
return any(_f for _f in self if _f) |
| 264 |
|
| 265 |
|
| 266 |
# TODO: replace with wx.DCPenChanger/wx.DCBrushChanger, etc. |
| 267 |
# Alternatively, replace those with this function... |
| 268 |
class TempStyle: |
| 269 |
"""Decorator / Context Manager to revert pen or brush changes. |
| 270 |
|
| 271 |
Will revert pen, brush, or both to their previous values after a method |
| 272 |
call or block finish. |
| 273 |
|
| 274 |
Args: |
| 275 |
which (str): The item to save and revert after execution. Can be |
| 276 |
one of ``{'both', 'pen', 'brush'}``. |
| 277 |
dc (wx.DC): The DC to get brush/pen info from. |
| 278 |
|
| 279 |
:: |
| 280 |
|
| 281 |
# Using as a method decorator: |
| 282 |
@TempStyle() # same as @TempStyle('both') |
| 283 |
def func(self, dc, a, b, c): # dc must be 1st arg (beside self) |
| 284 |
# edit pen and brush here |
| 285 |
|
| 286 |
# Or as a context manager: |
| 287 |
with TempStyle('both', dc): |
| 288 |
# do stuff |
| 289 |
|
| 290 |
.. Note:: |
| 291 |
|
| 292 |
As of 2016-06-15, this can only be used as a decorator for **class |
| 293 |
methods**, not standard functions. There is a plan to try and remove |
| 294 |
this restriction, but I don't know when that will happen... |
| 295 |
|
| 296 |
.. epigraph:: |
| 297 |
|
| 298 |
*Combination Decorator and Context Manager! Also makes Julienne fries! |
| 299 |
Will not break! Will not... It broke!* |
| 300 |
|
| 301 |
-- The Genie |
| 302 |
""" |
| 303 |
|
| 304 |
_valid_types: ClassVar[set[str]] = {"both", "pen", "brush"} |
| 305 |
_err_str = ( |
| 306 |
"No DC provided and unable to determine DC from context for function " |
| 307 |
"`{func_name}`. When `{cls_name}` is used as a decorator, the " |
| 308 |
"decorated function must have a wx.DC as a keyword arg 'dc=' or " |
| 309 |
"as the first arg." |
| 310 |
) |
| 311 |
|
| 312 |
def __init__(self, which="both", dc=None): |
| 313 |
if which not in self._valid_types: |
| 314 |
raise ValueError(f"`which` must be one of {self._valid_types}") |
| 315 |
self.which = which |
| 316 |
self.dc = dc |
| 317 |
self.prevPen = None |
| 318 |
self.prevBrush = None |
| 319 |
|
| 320 |
def __call__(self, func): |
| 321 |
"""Decorate the given function to apply the context manager. |
| 322 |
|
| 323 |
Args: |
| 324 |
func (callable): The function to decorate. |
| 325 |
|
| 326 |
Returns: |
| 327 |
callable: The decorated function that applies the context manager. |
| 328 |
""" |
| 329 |
|
| 330 |
@functools.wraps(func) |
| 331 |
def wrapper(instance, dc, *args, **kwargs): |
| 332 |
# fake the 'with' block. This solves: |
| 333 |
# 1. plots only being shown on 2nd menu selection in demo |
| 334 |
# 2. self.dc compalaining about not having a super called when |
| 335 |
# trying to get or set the pen/brush values in __enter__ and |
| 336 |
# __exit__: |
| 337 |
# RuntimeError: super-class __init__() of type |
| 338 |
# BufferedDC was never called |
| 339 |
self._save_items(dc) |
| 340 |
func(instance, dc, *args, **kwargs) |
| 341 |
self._revert_items(dc) |
| 342 |
|
| 343 |
# import copy # copy solves issue #1 above, but |
| 344 |
# self.dc = copy.copy(dc) # possibly causes issue #2. |
| 345 |
|
| 346 |
# with self: |
| 347 |
# print('in with') |
| 348 |
# func(instance, dc, *args, **kwargs) |
| 349 |
|
| 350 |
return wrapper |
| 351 |
|
| 352 |
def __enter__(self) -> Self: |
| 353 |
"""Enter the context manager. |
| 354 |
|
| 355 |
Returns: |
| 356 |
TempStyle: The current instance of the context manager. |
| 357 |
""" |
| 358 |
self._save_items(self.dc) |
| 359 |
return self |
| 360 |
|
| 361 |
def __exit__(self, exc_type, exc_value, traceback) -> bool: |
| 362 |
"""Exit the context manager. |
| 363 |
|
| 364 |
Args: |
| 365 |
exc_type: The exception type. |
| 366 |
exc_value: The exception value. |
| 367 |
traceback: The traceback object. |
| 368 |
|
| 369 |
Returns: |
| 370 |
bool: Always returns False. |
| 371 |
""" |
| 372 |
self._revert_items(self.dc) |
| 373 |
return False # True means exceptions *are* suppressed. |
| 374 |
|
| 375 |
def _save_items(self, dc): |
| 376 |
if self.which == "both": |
| 377 |
self._save_pen(dc) |
| 378 |
self._save_brush(dc) |
| 379 |
elif self.which == "pen": |
| 380 |
self._save_pen(dc) |
| 381 |
elif self.which == "brush": |
| 382 |
self._save_brush(dc) |
| 383 |
else: |
| 384 |
err_str = ( |
| 385 |
"How did you even get here?? This class forces " |
| 386 |
"correct values for `which` at instancing..." |
| 387 |
) |
| 388 |
raise ValueError(err_str) |
| 389 |
|
| 390 |
def _revert_items(self, dc): |
| 391 |
if self.which == "both": |
| 392 |
self._revert_pen(dc) |
| 393 |
self._revert_brush(dc) |
| 394 |
elif self.which == "pen": |
| 395 |
self._revert_pen(dc) |
| 396 |
elif self.which == "brush": |
| 397 |
self._revert_brush(dc) |
| 398 |
else: |
| 399 |
err_str = ( |
| 400 |
"How did you even get here?? This class forces " |
| 401 |
"correct values for `which` at instancing..." |
| 402 |
) |
| 403 |
raise ValueError(err_str) |
| 404 |
|
| 405 |
def _save_pen(self, dc): |
| 406 |
self.prevPen = dc.GetPen() |
| 407 |
|
| 408 |
def _save_brush(self, dc): |
| 409 |
self.prevBrush = dc.GetBrush() |
| 410 |
|
| 411 |
def _revert_pen(self, dc): |
| 412 |
dc.SetPen(self.prevPen) |
| 413 |
|
| 414 |
def _revert_brush(self, dc): |
| 415 |
dc.SetBrush(self.prevBrush) |
| 416 |
|
| 417 |
|
| 418 |
def scale_and_shift_point(x, y, scale=1, shift=0): |
| 419 |
"""Create a scaled and shifted 2x1 numpy array of [x, y] values. |
| 420 |
|
| 421 |
The shift value must be in the scaled units. |
| 422 |
|
| 423 |
Args: |
| 424 |
x (float): The x value of the unscaled, unshifted point. |
| 425 |
y (float): The y value of the unscaled, unshifted point. |
| 426 |
scale (np.array): The scale factor to use ``[x_scale, y_scale]``. |
| 427 |
shift (np.array): The offset to apply ``[x_shift, y_shift]``. |
| 428 |
Must be in scaled units |
| 429 |
|
| 430 |
Returns: |
| 431 |
np.array: A numpy array of 2 elements. |
| 432 |
|
| 433 |
.. note:: |
| 434 |
|
| 435 |
:math:`new = (scale * old) + shift` |
| 436 |
""" |
| 437 |
return scale * np.array([x, y]) + shift |
| 438 |
|
| 439 |
|
| 440 |
def set_display_side(value): |
| 441 |
"""Wrap around :class:`~wx.lib.plot._DisplaySide` to allow for "overloaded" calls. |
| 442 |
|
| 443 |
If ``value`` is a boolean: all 4 sides are set to ``value`` |
| 444 |
|
| 445 |
If ``value`` is a 2-tuple: the bottom and left sides are set to ``value`` |
| 446 |
and the other sides are set to False. |
| 447 |
|
| 448 |
If ``value`` is a 4-tuple, then each item is set individually: ``(bottom, |
| 449 |
left, top, right)`` |
| 450 |
|
| 451 |
Args: |
| 452 |
value (Union[bool, tuple(bool, bool), tuple(bool, bool, bool, bool)]): Which |
| 453 |
sides to display. |
| 454 |
|
| 455 |
Raises: |
| 456 |
TypeError: If setting an invalid value. |
| 457 |
ValueError: If the tuple has incorrect length. |
| 458 |
|
| 459 |
Returns: |
| 460 |
:class:`~wx.lib.plot._DisplaySide` |
| 461 |
""" |
| 462 |
err_txt = "value must be a bool or a 2- or 4-tuple of bool" |
| 463 |
|
| 464 |
# TODO: for 2-tuple, do not change other sides? rather than set to False. |
| 465 |
if isinstance(value, bool): |
| 466 |
# turns on or off all axes |
| 467 |
_value = (value, value, value, value) |
| 468 |
elif isinstance(value, tuple): |
| 469 |
if len(value) == 2: |
| 470 |
_value = (value[0], value[1], False, False) |
| 471 |
elif len(value) == 4: |
| 472 |
_value = value |
| 473 |
else: |
| 474 |
raise ValueError(err_txt) |
| 475 |
else: |
| 476 |
raise TypeError(err_txt) |
| 477 |
return DisplaySide(*_value) |
| 478 |
|
| 479 |
|
| 480 |
# ---------------------------------------------------------------------- |
| 481 |
# |
| 482 |
# Plotting classes... |
| 483 |
# |
| 484 |
class PolyPoints: |
| 485 |
"""Base Class for lines and markers. |
| 486 |
|
| 487 |
Args: |
| 488 |
points (list[tuple(float, float)]): Sequence (array, tuple or list) of |
| 489 |
(x,y) points making up line or marker. |
| 490 |
attr (dict): Key word attributes: |
| 491 |
Defaults: |
| 492 |
'legend'= '' - Legend to display |
| 493 |
""" |
| 494 |
|
| 495 |
def __init__(self, points, attr): |
| 496 |
self._points = np.array(points).astype(np.float64) |
| 497 |
self._logscale = (False, False) |
| 498 |
self._pointSize = (1.0, 1.0) |
| 499 |
self.currentScale = (1, 1) |
| 500 |
self.currentShift = (0, 0) |
| 501 |
self.scaled = self.points |
| 502 |
self.attributes = {} |
| 503 |
self.attributes.update(self._attributes) |
| 504 |
for name, value in list(attr.items()): |
| 505 |
if name not in list(self._attributes.keys()): |
| 506 |
raise KeyError( |
| 507 |
"Style attribute incorrect. Should be one of " |
| 508 |
f"{list(self._attributes.keys())}" |
| 509 |
) |
| 510 |
self.attributes[name] = value |
| 511 |
|
| 512 |
def setLogScale(self, logscale): |
| 513 |
"""Set the log scale for the x and y axes. |
| 514 |
|
| 515 |
Args: |
| 516 |
logscale (tuple): A tuple of two booleans indicating whether to |
| 517 |
use log scale for the x and y axes, respectively. |
| 518 |
""" |
| 519 |
self._logscale = logscale |
| 520 |
|
| 521 |
def __getattr__(self, name): |
| 522 |
"""Return the points. |
| 523 |
|
| 524 |
Args: |
| 525 |
name (str): The name of the attribute to get. Anything other than |
| 526 |
"points" will raise an AttributeError. |
| 527 |
|
| 528 |
Raises: |
| 529 |
AttributeError: If the attribute name is not "points". |
| 530 |
|
| 531 |
Returns: |
| 532 |
np.array: The points in the specified format. |
| 533 |
""" |
| 534 |
if name != "points": |
| 535 |
raise AttributeError(name) |
| 536 |
if len(self._points) > 0: |
| 537 |
data = np.array(self._points, copy=True) |
| 538 |
if self._logscale[0]: |
| 539 |
data = self.log10(data, 0) |
| 540 |
if self._logscale[1]: |
| 541 |
data = self.log10(data, 1) |
| 542 |
return data |
| 543 |
return self._points |
| 544 |
|
| 545 |
def log10(self, data, ind): |
| 546 |
"""Convert data to log10 scale for the specified index. |
| 547 |
|
| 548 |
Args: |
| 549 |
data (np.array): The data to convert. |
| 550 |
ind (int): The index of the column to convert to log10 scale. |
| 551 |
|
| 552 |
Returns: |
| 553 |
np.array: The data with the specified column converted to log10 scale. |
| 554 |
""" |
| 555 |
data = np.compress(data[:, ind] > 0, data, 0) |
| 556 |
data[:, ind] = np.log10(data[:, ind]) |
| 557 |
return data |
| 558 |
|
| 559 |
def boundingBox(self): |
| 560 |
"""Calculate the bounding box of the points. |
| 561 |
|
| 562 |
Returns: |
| 563 |
tuple: A tuple containing two points (minXY, maxXY) representing |
| 564 |
the bounding box of the points. |
| 565 |
""" |
| 566 |
if len(self.points) == 0: |
| 567 |
# no curves to draw |
| 568 |
# defaults to (-1,-1) and (1,1) but axis can be set in Draw |
| 569 |
minXY = np.array([-1.0, -1.0]) |
| 570 |
maxXY = np.array([1.0, 1.0]) |
| 571 |
else: |
| 572 |
minXY = np.minimum.reduce(self.points) |
| 573 |
maxXY = np.maximum.reduce(self.points) |
| 574 |
return minXY, maxXY |
| 575 |
|
| 576 |
def scaleAndShift(self, scale=(1, 1), shift=(0, 0)): |
| 577 |
"""Scale and shift the points. |
| 578 |
|
| 579 |
Args: |
| 580 |
scale (tuple): The scale factor to use for the x and y axes. |
| 581 |
Default is (1, 1). |
| 582 |
shift (tuple): The offset to apply to the x and y axes. |
| 583 |
Default is (0, 0). |
| 584 |
""" |
| 585 |
if len(self.points) == 0: |
| 586 |
# no curves to draw |
| 587 |
return |
| 588 |
if (scale is not self.currentScale) or (shift is not self.currentShift): |
| 589 |
# update point scaling |
| 590 |
self.scaled = scale * self.points + shift |
| 591 |
self.currentScale = scale |
| 592 |
self.currentShift = shift |
| 593 |
# else unchanged use the current scaling |
| 594 |
|
| 595 |
def getLegend(self): |
| 596 |
"""Return the legend for the curve. |
| 597 |
|
| 598 |
Returns: |
| 599 |
str: The legend for the curve. |
| 600 |
""" |
| 601 |
return self.attributes["legend"] |
| 602 |
|
| 603 |
def getClosestPoint(self, pntXY, pointScaled=True): |
| 604 |
"""Return the index of the closest point on the curve. |
| 605 |
|
| 606 |
Return the index of closest point on the curve, pointXY, scaledXY, |
| 607 |
distance x, y in user coords |
| 608 |
if pointScaled == True based on screen coords |
| 609 |
if pointScaled == False based on user coords |
| 610 |
|
| 611 |
Args: |
| 612 |
pntXY (tuple): The (x, y) coordinates of the point to find the |
| 613 |
closest point to. |
| 614 |
pointScaled (bool): If True, use screen coordinates; if False, |
| 615 |
use user coordinates. Default is True. |
| 616 |
|
| 617 |
Returns: |
| 618 |
list: A list containing the index of the closest point, the |
| 619 |
coordinates of the closest point, the scaled coordinates of the |
| 620 |
closest point, and the distance to the closest point. |
| 621 |
""" |
| 622 |
if pointScaled is True: |
| 623 |
# Using screen coords |
| 624 |
p = self.scaled |
| 625 |
pxy = self.currentScale * np.array(pntXY) + self.currentShift |
| 626 |
else: |
| 627 |
# Using user coords |
| 628 |
p = self.points |
| 629 |
pxy = np.array(pntXY) |
| 630 |
# determine distance for each point |
| 631 |
d = np.sqrt(np.add.reduce((p - pxy) ** 2, 1)) # sqrt(dx^2+dy^2) |
| 632 |
pntIndex = np.argmin(d) |
| 633 |
dist = d[pntIndex] |
| 634 |
return [ |
| 635 |
pntIndex, |
| 636 |
self.points[pntIndex], |
| 637 |
self.scaled[pntIndex] / self._pointSize, |
| 638 |
dist, |
| 639 |
] |
| 640 |
|
| 641 |
|
| 642 |
class PolyLine(PolyPoints): |
| 643 |
"""Class to define line type and style. |
| 644 |
|
| 645 |
All methods except __init__ are private. |
| 646 |
|
| 647 |
Args: |
| 648 |
points (list[tuple(float, float)]): Sequence (array, tuple or list) of |
| 649 |
(x,y) points making up line. |
| 650 |
attr (dict): Key word attributes: |
| 651 |
Defaults: |
| 652 |
'colour'= 'black', - wx.Pen Colour any wx.NamedColour |
| 653 |
'width'= 1, - Pen width |
| 654 |
'style'= wx.PENSTYLE_SOLID, - wx.Pen style |
| 655 |
'legend'= '' - Line Legend to display |
| 656 |
""" |
| 657 |
|
| 658 |
_attributes: ClassVar[dict] = { |
| 659 |
"colour": "black", |
| 660 |
"width": 1, |
| 661 |
"style": wx.PENSTYLE_SOLID, |
| 662 |
"legend": "", |
| 663 |
} |
| 664 |
|
| 665 |
def __init__(self, points, **attr): |
| 666 |
PolyPoints.__init__(self, points, attr) |
| 667 |
|
| 668 |
def draw(self, dc, printerScale, coord=None): |
| 669 |
"""Draw the line on the given device context (dc). |
| 670 |
|
| 671 |
Args: |
| 672 |
dc (wx.DC): The device context to draw on. |
| 673 |
printerScale (float): The scale factor for printing. |
| 674 |
coord (None | list[tuple(float, float)]): Coordinates to draw the |
| 675 |
line at. If None, uses the object's scaled coordinates. |
| 676 |
""" |
| 677 |
colour = self.attributes["colour"] |
| 678 |
width = self.attributes["width"] * printerScale * self._pointSize[0] |
| 679 |
style = self.attributes["style"] |
| 680 |
if not isinstance(colour, wx.Colour): |
| 681 |
colour = wx.NamedColour(colour) |
| 682 |
pen = wx.Pen(colour, int(width), style) |
| 683 |
pen.SetCap(wx.CAP_BUTT) |
| 684 |
dc.SetPen(pen) |
| 685 |
if coord is None: |
| 686 |
if len(self.scaled): # bugfix for Mac OS X |
| 687 |
if wx.VERSION >= (4,) and isinstance(self.scaled, np.ndarray): |
| 688 |
# Need to convert to list of tuples |
| 689 |
scaled = convert_to_list_of_tuples(self.scaled) |
| 690 |
dc.DrawLines(scaled) |
| 691 |
else: |
| 692 |
dc.DrawLines(self.scaled) |
| 693 |
else: |
| 694 |
dc.DrawLines(coord) # draw legend line |
| 695 |
|
| 696 |
def getSymExtent(self, printerScale): |
| 697 |
"""Width and Height of Marker.""" |
| 698 |
h = self.attributes["width"] * printerScale * self._pointSize[0] |
| 699 |
w = 7 * h |
| 700 |
return (w, h) |
| 701 |
|
| 702 |
|
| 703 |
class PolySpline(PolyLine): |
| 704 |
"""Class to define line type and style. |
| 705 |
|
| 706 |
- All methods except __init__ are private. |
| 707 |
|
| 708 |
|
| 709 |
Args: |
| 710 |
points: sequence (array, tuple or list) of (x,y) points making up line |
| 711 |
**attr - key word attributes. |
| 712 |
|
| 713 |
Defaults: |
| 714 |
'colour'= 'black', - wx.Pen Colour any wx.NamedColour |
| 715 |
'width'= 1, - Pen width |
| 716 |
'style'= wx.PENSTYLE_SOLID, - wx.Pen style |
| 717 |
'legend'= '' - Line Legend to display |
| 718 |
""" |
| 719 |
|
| 720 |
_attributes: ClassVar[dict] = { |
| 721 |
"colour": "black", |
| 722 |
"width": 1, |
| 723 |
"style": wx.PENSTYLE_SOLID, |
| 724 |
"legend": "", |
| 725 |
} |
| 726 |
|
| 727 |
def __init__(self, points, **attr): |
| 728 |
PolyLine.__init__(self, points, **attr) |
| 729 |
|
| 730 |
def draw(self, dc, printerScale, coord=None): |
| 731 |
"""Draw the spline on the given device context (dc). |
| 732 |
|
| 733 |
Args: |
| 734 |
dc (wx.DC): The device context to draw on. |
| 735 |
printerScale (float): The scale factor for printing. |
| 736 |
coord (None | list[tuple(float, float)]): Coordinates to draw the |
| 737 |
spline at. If None, uses the object's scaled coordinates. |
| 738 |
""" |
| 739 |
colour = self.attributes["colour"] |
| 740 |
width = self.attributes["width"] * printerScale * self._pointSize[0] |
| 741 |
style = self.attributes["style"] |
| 742 |
if not isinstance(colour, wx.Colour): |
| 743 |
colour = wx.NamedColour(colour) |
| 744 |
pen = wx.Pen(colour, int(width), style) |
| 745 |
pen.SetCap(wx.CAP_ROUND) |
| 746 |
dc.SetPen(pen) |
| 747 |
if coord is None: |
| 748 |
if len(self.scaled): # bugfix for Mac OS X |
| 749 |
if wx.VERSION >= (4,) and isinstance(self.scaled, np.ndarray): |
| 750 |
# Need to convert to list of tuples |
| 751 |
scaled = convert_to_list_of_tuples(self.scaled) |
| 752 |
dc.DrawSpline(scaled) |
| 753 |
else: |
| 754 |
dc.DrawSpline(self.scaled) |
| 755 |
else: |
| 756 |
dc.DrawLines(coord) # draw legend line |
| 757 |
|
| 758 |
|
| 759 |
class PolyMarker(PolyPoints): |
| 760 |
"""Class to define marker type and style. |
| 761 |
|
| 762 |
Create PolyMarker object |
| 763 |
points - sequence (array, tuple or list) of (x,y) points |
| 764 |
**attr - key word attributes |
| 765 |
Defaults: |
| 766 |
'colour'= 'black', - wx.Pen Colour any wx.NamedColour |
| 767 |
'width'= 1, - Pen width |
| 768 |
'size'= 2, - Marker size |
| 769 |
'fillcolour'= same as colour, - wx.Brush Colour any wx.NamedColour |
| 770 |
'fillstyle'= wx.BRUSHSTYLE_SOLID, - wx.Brush fill style (use |
| 771 |
wx.BRUSHSTYLE_TRANSPARENT for no |
| 772 |
fill) |
| 773 |
'marker'= 'circle' - Marker shape |
| 774 |
'legend'= '' - Marker Legend to display |
| 775 |
|
| 776 |
Marker Shapes: |
| 777 |
- 'circle' |
| 778 |
- 'dot' |
| 779 |
- 'square' |
| 780 |
- 'triangle' |
| 781 |
- 'triangle_down' |
| 782 |
- 'cross' |
| 783 |
- 'plus' |
| 784 |
""" |
| 785 |
|
| 786 |
_attributes: ClassVar[dict] = { |
| 787 |
"colour": "black", |
| 788 |
"width": 1, |
| 789 |
"size": 2, |
| 790 |
"fillcolour": None, |
| 791 |
"fillstyle": wx.BRUSHSTYLE_SOLID, |
| 792 |
"marker": "circle", |
| 793 |
"legend": "", |
| 794 |
} |
| 795 |
|
| 796 |
def __init__(self, points, **attr): |
| 797 |
PolyPoints.__init__(self, points, attr) |
| 798 |
|
| 799 |
def draw(self, dc, printerScale, coord=None): |
| 800 |
"""Draw the marker on the given device context (dc). |
| 801 |
|
| 802 |
Args: |
| 803 |
dc (wx.DC): The device context to draw on. |
| 804 |
printerScale (float): The scale factor for printing. |
| 805 |
coord (None | list[tuple(float, float)]): Coordinates to draw the |
| 806 |
marker at. If None, uses the object's scaled coordinates. |
| 807 |
""" |
| 808 |
colour = self.attributes["colour"] |
| 809 |
width = self.attributes["width"] * printerScale * self._pointSize[0] |
| 810 |
size = self.attributes["size"] * printerScale * self._pointSize[0] |
| 811 |
fillcolour = self.attributes["fillcolour"] |
| 812 |
fillstyle = self.attributes["fillstyle"] |
| 813 |
marker = self.attributes["marker"] |
| 814 |
|
| 815 |
if colour and not isinstance(colour, wx.Colour): |
| 816 |
colour = wx.NamedColour(colour) |
| 817 |
if fillcolour and not isinstance(fillcolour, wx.Colour): |
| 818 |
fillcolour = wx.NamedColour(fillcolour) |
| 819 |
|
| 820 |
dc.SetPen(wx.Pen(colour, int(width))) |
| 821 |
if fillcolour: |
| 822 |
dc.SetBrush(wx.Brush(fillcolour, fillstyle)) |
| 823 |
else: |
| 824 |
dc.SetBrush(wx.Brush(colour, fillstyle)) |
| 825 |
if coord is None: |
| 826 |
if len(self.scaled): # bugfix for Mac OS X |
| 827 |
self._drawmarkers(dc, self.scaled, marker, size) |
| 828 |
else: |
| 829 |
self._drawmarkers(dc, coord, marker, size) # draw legend marker |
| 830 |
|
| 831 |
def getSymExtent(self, printerScale): |
| 832 |
"""Width and Height of Marker.""" |
| 833 |
s = 7 * self.attributes["size"] * printerScale * self._pointSize[0] |
| 834 |
return (s, s) |
| 835 |
|
| 836 |
def _drawmarkers(self, dc, coords, marker, size=1): |
| 837 |
f = getattr(self, f"_{marker}") |
| 838 |
f(dc, coords, size) |
| 839 |
|
| 840 |
def _circle(self, dc, coords, size=1): |
| 841 |
fact = 2.5 * size |
| 842 |
wh = 5.0 * size |
| 843 |
rect = np.zeros((len(coords), 4), float) + [0.0, 0.0, wh, wh] # noqa: RUF005 |
| 844 |
rect[:, 0:2] = coords - [fact, fact] |
| 845 |
dc.DrawEllipseList(rect.astype(np.int32)) |
| 846 |
|
| 847 |
def _dot(self, dc, coords, size=1): |
| 848 |
dc.DrawPointList(coords) |
| 849 |
|
| 850 |
def _square(self, dc, coords, size=1): |
| 851 |
fact = 2.5 * size |
| 852 |
wh = 5.0 * size |
| 853 |
rect = np.zeros((len(coords), 4), float) + [0.0, 0.0, wh, wh] # noqa: RUF005 |
| 854 |
rect[:, 0:2] = coords - [fact, fact] |
| 855 |
dc.DrawRectangleList(rect.astype(np.int32)) |
| 856 |
|
| 857 |
def _triangle(self, dc, coords, size=1): |
| 858 |
shape = [ |
| 859 |
(-2.5 * size, 1.44 * size), |
| 860 |
(2.5 * size, 1.44 * size), |
| 861 |
(0.0, -2.88 * size), |
| 862 |
] |
| 863 |
poly = np.repeat(coords, 3, 0) |
| 864 |
poly.shape = (len(coords), 3, 2) |
| 865 |
poly += shape |
| 866 |
dc.DrawPolygonList(poly.astype(np.int32)) |
| 867 |
|
| 868 |
def _triangle_down(self, dc, coords, size=1): |
| 869 |
shape = [ |
| 870 |
(-2.5 * size, -1.44 * size), |
| 871 |
(2.5 * size, -1.44 * size), |
| 872 |
(0.0, 2.88 * size), |
| 873 |
] |
| 874 |
poly = np.repeat(coords, 3, 0) |
| 875 |
poly.shape = (len(coords), 3, 2) |
| 876 |
poly += shape |
| 877 |
dc.DrawPolygonList(poly.astype(np.int32)) |
| 878 |
|
| 879 |
def _cross(self, dc, coords, size=1): |
| 880 |
fact = 2.5 * size |
| 881 |
for f in [[-fact, -fact, fact, fact], [-fact, fact, fact, -fact]]: |
| 882 |
lines = np.concatenate((coords, coords), axis=1) + f |
| 883 |
dc.DrawLineList(lines.astype(np.int32)) |
| 884 |
|
| 885 |
def _plus(self, dc, coords, size=1): |
| 886 |
fact = 2.5 * size |
| 887 |
for f in [[-fact, 0, fact, 0], [0, -fact, 0, fact]]: |
| 888 |
lines = np.concatenate((coords, coords), axis=1) + f |
| 889 |
dc.DrawLineList(lines.astype(np.int32)) |
| 890 |
|
| 891 |
|
| 892 |
class PlotGraphics: |
| 893 |
"""Container to hold PolyXXX objects and graph labels. |
| 894 |
|
| 895 |
Args: |
| 896 |
objects (list[PolyXXX]): List of PolyXXX objects to make graph. |
| 897 |
title (str): The title shown at top of graph. |
| 898 |
xLabel (str): The label shown on x-axis. |
| 899 |
yLabel (str): The label shown on y-axis |
| 900 |
""" |
| 901 |
|
| 902 |
def __init__(self, objects, title="", xLabel="", yLabel=""): |
| 903 |
if not isinstance(objects, (list, tuple)): |
| 904 |
raise TypeError("objects argument should be list or tuple") |
| 905 |
self.objects = objects |
| 906 |
self.title = title |
| 907 |
self.xLabel = xLabel |
| 908 |
self.yLabel = yLabel |
| 909 |
self._pointSize = (1.0, 1.0) |
| 910 |
|
| 911 |
def setLogScale(self, logscale): |
| 912 |
"""Set the log scale for the x and y axes. |
| 913 |
|
| 914 |
Args: |
| 915 |
logscale (tuple): A tuple of two booleans indicating whether to |
| 916 |
use log scale for the x and y axes, respectively. |
| 917 |
|
| 918 |
Raises: |
| 919 |
TypeError: If logscale is not a tuple of two booleans. |
| 920 |
""" |
| 921 |
if not isinstance(logscale, tuple): |
| 922 |
raise TypeError("logscale must be a tuple of bools, e.g. (False, False)") |
| 923 |
if len(self.objects) == 0: |
| 924 |
return |
| 925 |
for o in self.objects: |
| 926 |
o.setLogScale(logscale) |
| 927 |
|
| 928 |
def boundingBox(self): |
| 929 |
"""Calculate the bounding box of all objects in the plot. |
| 930 |
|
| 931 |
Returns: |
| 932 |
tuple: A tuple containing two points (p1, p2) representing the |
| 933 |
bounding box of the plot. |
| 934 |
""" |
| 935 |
p1, p2 = self.objects[0].boundingBox() |
| 936 |
for o in self.objects[1:]: |
| 937 |
p1o, p2o = o.boundingBox() |
| 938 |
p1 = np.minimum(p1, p1o) |
| 939 |
p2 = np.maximum(p2, p2o) |
| 940 |
return p1, p2 |
| 941 |
|
| 942 |
def scaleAndShift(self, scale=(1, 1), shift=(0, 0)): |
| 943 |
"""Scale and shift all objects in the plot. |
| 944 |
|
| 945 |
Args: |
| 946 |
scale (tuple): The scale factor to use for the x and y axes. |
| 947 |
shift (tuple): The offset to apply to the x and y axes. |
| 948 |
""" |
| 949 |
for o in self.objects: |
| 950 |
o.scaleAndShift(scale, shift) |
| 951 |
|
| 952 |
def setPrinterScale(self, scale: float) -> None: |
| 953 |
"""Thicken up lines and markers only for printing. |
| 954 |
|
| 955 |
Args: |
| 956 |
scale (float): The scale factor to use for printing. |
| 957 |
""" |
| 958 |
self.printerScale = scale |
| 959 |
|
| 960 |
def setXLabel(self, xLabel: None | str = None) -> None: |
| 961 |
"""Set the X axis label on the graph. |
| 962 |
|
| 963 |
Args: |
| 964 |
xLabel (str): The label to set for the x-axis. |
| 965 |
""" |
| 966 |
if xLabel is None: |
| 967 |
xLabel = "" |
| 968 |
self.xLabel = xLabel |
| 969 |
|
| 970 |
def setYLabel(self, yLabel: None | str = None) -> None: |
| 971 |
"""Set the Y axis label on the graph. |
| 972 |
|
| 973 |
Args: |
| 974 |
yLabel (str): The label to set for the y-axis. |
| 975 |
""" |
| 976 |
if yLabel is None: |
| 977 |
yLabel = "" |
| 978 |
self.yLabel = yLabel |
| 979 |
|
| 980 |
def setTitle(self, title=None): |
| 981 |
"""Set the title at the top of graph. |
| 982 |
|
| 983 |
Args: |
| 984 |
title (str): The title to set. |
| 985 |
""" |
| 986 |
if title is None: |
| 987 |
title = "" |
| 988 |
self.title = title |
| 989 |
|
| 990 |
def getXLabel(self): |
| 991 |
"""Get x axis label text. |
| 992 |
|
| 993 |
Returns: |
| 994 |
str: The label of the x-axis. |
| 995 |
""" |
| 996 |
return self.xLabel |
| 997 |
|
| 998 |
def getYLabel(self): |
| 999 |
"""Get y axis label text. |
| 1000 |
|
| 1001 |
Returns: |
| 1002 |
str: The label of the y-axis. |
| 1003 |
""" |
| 1004 |
return self.yLabel |
| 1005 |
|
| 1006 |
def getTitle(self, title=""): |
| 1007 |
"""Get the title at the top of graph. |
| 1008 |
|
| 1009 |
Args: |
| 1010 |
title (str): The title to return. If not provided, the current |
| 1011 |
title is returned. |
| 1012 |
|
| 1013 |
Returns: |
| 1014 |
str: The title of the graph. |
| 1015 |
""" |
| 1016 |
return self.title |
| 1017 |
|
| 1018 |
def draw(self, dc): |
| 1019 |
"""Draw the graph on the given device context (dc). |
| 1020 |
|
| 1021 |
Args: |
| 1022 |
dc (wx.DC): The device context to draw on. |
| 1023 |
""" |
| 1024 |
for o in self.objects: |
| 1025 |
# t=_time.time() # profile info |
| 1026 |
o._pointSize = self._pointSize |
| 1027 |
o.draw(dc, self.printerScale) |
| 1028 |
# dt= _time.time() - t |
| 1029 |
# print o, "time=", dt |
| 1030 |
|
| 1031 |
def getSymExtent(self, printerScale): |
| 1032 |
"""Get max width and height of lines and markers symbols for legend.""" |
| 1033 |
self.objects[0]._pointSize = self._pointSize |
| 1034 |
symExt = self.objects[0].getSymExtent(printerScale) |
| 1035 |
for o in self.objects[1:]: |
| 1036 |
o._pointSize = self._pointSize |
| 1037 |
oSymExt = o.getSymExtent(printerScale) |
| 1038 |
symExt = np.maximum(symExt, oSymExt) |
| 1039 |
return symExt |
| 1040 |
|
| 1041 |
def getLegendNames(self): |
| 1042 |
"""Return list of legend names.""" |
| 1043 |
lst = [] |
| 1044 |
for obj in self.objects: |
| 1045 |
legend = obj.getLegend() |
| 1046 |
if legend: |
| 1047 |
lst.append(legend) |
| 1048 |
return lst |
| 1049 |
|
| 1050 |
def __len__(self) -> int: |
| 1051 |
"""Get the number of objects in the list. |
| 1052 |
|
| 1053 |
Returns: |
| 1054 |
int: The number of objects in the list. |
| 1055 |
""" |
| 1056 |
return len(self.objects) |
| 1057 |
|
| 1058 |
def __getitem__(self, item) -> PolyLine | PolyMarker | PolyPoints | PolySpline: |
| 1059 |
"""Get item from objects list. |
| 1060 |
|
| 1061 |
Args: |
| 1062 |
item (int): The index of the object to get. |
| 1063 |
|
| 1064 |
Returns: |
| 1065 |
PolyXXX: The object at the given index. |
| 1066 |
""" |
| 1067 |
return self.objects[item] |
| 1068 |
|
| 1069 |
|
| 1070 |
# ------------------------------------------------------------------------------- |
| 1071 |
# Main window that you will want to import into your application. |
| 1072 |
|
| 1073 |
|
| 1074 |
class PlotCanvas(wx.Panel): |
| 1075 |
"""wx.Panel derivative which holds two scroll bars and the actual plotting canvas. |
| 1076 |
|
| 1077 |
It allows for simple general plotting of data with zoom, labels, and |
| 1078 |
automatic axis scaling. |
| 1079 |
|
| 1080 |
Constructs a panel, which can be a child of a frame or any other |
| 1081 |
non-control window. |
| 1082 |
|
| 1083 |
Args: |
| 1084 |
parent (wx.Window): The parent window for this panel. |
| 1085 |
id (int): The identifier for the panel. Default is wx.ID_ANY. |
| 1086 |
pos (wx.Point): The position of the panel. Default is wx.DefaultPosition. |
| 1087 |
size (wx.Size): The size of the panel. Default is wx.DefaultSize. |
| 1088 |
style (int): The style of the panel. Default is 0. |
| 1089 |
name (str): The name of the panel. Default is "plotCanvas". |
| 1090 |
""" |
| 1091 |
|
| 1092 |
def __init__( |
| 1093 |
self, |
| 1094 |
parent, |
| 1095 |
id=wx.ID_ANY, # noqa: A002 |
| 1096 |
pos=wx.DefaultPosition, |
| 1097 |
size=wx.DefaultSize, |
| 1098 |
style=0, |
| 1099 |
name=None, |
| 1100 |
): |
| 1101 |
if name is None: |
| 1102 |
name = "plotCanvas" |
| 1103 |
wx.Panel.__init__(self, parent, id, pos, size, style, name) |
| 1104 |
|
| 1105 |
self._multiples = [(2.0, np.log10(2.0)), (5.0, np.log10(5.0))] |
| 1106 |
|
| 1107 |
sizer = wx.FlexGridSizer(2, 2, 0, 0) |
| 1108 |
self.canvas = wx.Window(self, -1) |
| 1109 |
self.sb_vert = wx.ScrollBar(self, -1, style=wx.SB_VERTICAL) |
| 1110 |
self.sb_vert.SetScrollbar(0, 1000, 1000, 1000) |
| 1111 |
self.sb_hor = wx.ScrollBar(self, -1, style=wx.SB_HORIZONTAL) |
| 1112 |
self.sb_hor.SetScrollbar(0, 1000, 1000, 1000) |
| 1113 |
|
| 1114 |
sizer.Add(self.canvas, 1, wx.EXPAND) |
| 1115 |
sizer.Add(self.sb_vert, 0, wx.EXPAND) |
| 1116 |
sizer.Add(self.sb_hor, 0, wx.EXPAND) |
| 1117 |
sizer.Add((0, 0)) |
| 1118 |
|
| 1119 |
sizer.AddGrowableRow(0, 1) |
| 1120 |
sizer.AddGrowableCol(0, 1) |
| 1121 |
|
| 1122 |
self.sb_vert.Show(False) |
| 1123 |
self.sb_hor.Show(False) |
| 1124 |
|
| 1125 |
self.SetSizer(sizer) |
| 1126 |
self.Fit() |
| 1127 |
|
| 1128 |
self.border = (1, 1) |
| 1129 |
|
| 1130 |
self.SetBackgroundColour("white") |
| 1131 |
|
| 1132 |
# Create some mouse events for zooming |
| 1133 |
self.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown) |
| 1134 |
self.canvas.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp) |
| 1135 |
self.canvas.Bind(wx.EVT_MOTION, self.OnMotion) |
| 1136 |
self.canvas.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDoubleClick) |
| 1137 |
self.canvas.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown) |
| 1138 |
|
| 1139 |
# scrollbar events |
| 1140 |
self.Bind(wx.EVT_SCROLL_THUMBTRACK, self.OnScroll) |
| 1141 |
self.Bind(wx.EVT_SCROLL_PAGEUP, self.OnScroll) |
| 1142 |
self.Bind(wx.EVT_SCROLL_PAGEDOWN, self.OnScroll) |
| 1143 |
self.Bind(wx.EVT_SCROLL_LINEUP, self.OnScroll) |
| 1144 |
self.Bind(wx.EVT_SCROLL_LINEDOWN, self.OnScroll) |
| 1145 |
|
| 1146 |
# set curser as cross-hairs |
| 1147 |
self.canvas.SetCursor(wx.CROSS_CURSOR) |
| 1148 |
self.HandCursor = wx.CursorFromImage(Hand.GetImage()) |
| 1149 |
self.GrabHandCursor = wx.CursorFromImage(GrabHand.GetImage()) |
| 1150 |
self.MagCursor = wx.CursorFromImage(MagPlus.GetImage()) |
| 1151 |
|
| 1152 |
# Things for printing |
| 1153 |
self._print_data = None |
| 1154 |
self._pageSetupData = None |
| 1155 |
self.printerScale = 1 |
| 1156 |
self.parent = parent |
| 1157 |
|
| 1158 |
# scrollbar variables |
| 1159 |
self._sb_ignore = False |
| 1160 |
self._adjustingSB = False |
| 1161 |
self._sb_xfullrange = 0 |
| 1162 |
self._sb_yfullrange = 0 |
| 1163 |
self._sb_xunit = 0 |
| 1164 |
self._sb_yunit = 0 |
| 1165 |
|
| 1166 |
self._dragEnabled = False |
| 1167 |
self._screenCoordinates = np.array([0.0, 0.0]) |
| 1168 |
|
| 1169 |
self._logscale = (False, False) |
| 1170 |
|
| 1171 |
# Zooming variables |
| 1172 |
self._zoomInFactor = 0.5 |
| 1173 |
self._zoomOutFactor = 2 |
| 1174 |
self._zoomCorner1 = np.array([0.0, 0.0]) # left mouse down corner |
| 1175 |
self._zoomCorner2 = np.array([0.0, 0.0]) # left mouse up corner |
| 1176 |
self._zoomEnabled = False |
| 1177 |
self._hasDragged = False |
| 1178 |
|
| 1179 |
# Drawing Variables |
| 1180 |
self.last_draw = None |
| 1181 |
self._pointScale = 1 |
| 1182 |
self._pointShift = 0 |
| 1183 |
self._xSpec = "auto" |
| 1184 |
self._ySpec = "auto" |
| 1185 |
self._gridEnabled = False |
| 1186 |
self._legendEnabled = False |
| 1187 |
self._titleEnabled = True |
| 1188 |
self._centerLinesEnabled = False |
| 1189 |
self._diagonalsEnabled = False |
| 1190 |
self._ticksEnabled = DisplaySide(False, False, False, False) |
| 1191 |
|
| 1192 |
# Fonts |
| 1193 |
self._fontCache = {} |
| 1194 |
self._fontSizeAxis = 10 |
| 1195 |
self._fontSizeTitle = 15 |
| 1196 |
self._fontSizeLegend = 7 |
| 1197 |
|
| 1198 |
# pointLabels |
| 1199 |
self._pointLabelEnabled = False |
| 1200 |
self.last_PointLabel = None |
| 1201 |
self._pointLabelFunc = None |
| 1202 |
self.canvas.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave) |
| 1203 |
self._logicalFunction = wx.COPY # wx.EQUIV not supported on Mac OS X |
| 1204 |
|
| 1205 |
self._useScientificNotation = False |
| 1206 |
|
| 1207 |
self._antiAliasingEnabled = False |
| 1208 |
self._hiResEnabled = False |
| 1209 |
self._pointSize = (1.0, 1.0) |
| 1210 |
self._fontScale = 1.0 |
| 1211 |
|
| 1212 |
self.canvas.Bind(wx.EVT_PAINT, self.OnPaint) |
| 1213 |
self.canvas.Bind(wx.EVT_SIZE, self.OnSize) |
| 1214 |
# OnSize called to make sure the buffer is initialized. |
| 1215 |
# This might result in OnSize getting called twice on some |
| 1216 |
# platforms at initialization, but little harm done. |
| 1217 |
self.OnSize(None) # sets the initial size based on client size |
| 1218 |
|
| 1219 |
self._gridColour = wx.NamedColour("black") |
| 1220 |
|
| 1221 |
# Default Pens |
| 1222 |
self._tickPen = wx.Pen(wx.BLACK, int(self._pointSize[0])) |
| 1223 |
self._tickLength = tuple(-x * 2 for x in self._pointSize) |
| 1224 |
|
| 1225 |
def SetCursor(self, cursor): |
| 1226 |
"""Set the cursor for the canvas. |
| 1227 |
|
| 1228 |
Args: |
| 1229 |
cursor (wx.Cursor): The cursor to set for the canvas. |
| 1230 |
""" |
| 1231 |
self.canvas.SetCursor(cursor) |
| 1232 |
|
| 1233 |
def GetGridColour(self): |
| 1234 |
"""Get the colour of the grid lines. |
| 1235 |
|
| 1236 |
Returns: |
| 1237 |
wx.Colour: The colour of the grid lines. |
| 1238 |
""" |
| 1239 |
return self._gridColour |
| 1240 |
|
| 1241 |
def SetGridColour(self, colour): |
| 1242 |
"""Set the colour of the grid lines. |
| 1243 |
|
| 1244 |
Args: |
| 1245 |
colour (str or wx.Colour): The colour to set the grid lines to. |
| 1246 |
""" |
| 1247 |
if isinstance(colour, wx.Colour): |
| 1248 |
self._gridColour = colour |
| 1249 |
else: |
| 1250 |
self._gridColour = wx.NamedColour(colour) |
| 1251 |
|
| 1252 |
@property |
| 1253 |
def tickPen(self): |
| 1254 |
"""The :class:`wx.Pen` used to draw the tick marks on the plot. |
| 1255 |
|
| 1256 |
:getter: Returns the :class:`wx.Pen` used for drawing the tick marks. |
| 1257 |
:setter: Sets the :class:`wx.Pen` use for drawging the tick marks. |
| 1258 |
:type: :class:`wx.Pen` |
| 1259 |
:raise: `TypeError` when setting a value that is not a |
| 1260 |
:class:`wx.Pen`. |
| 1261 |
""" |
| 1262 |
return self._tickPen |
| 1263 |
|
| 1264 |
@tickPen.setter |
| 1265 |
def tickPen(self, pen): |
| 1266 |
if not isinstance(pen, wx.Pen): |
| 1267 |
raise TypeError("pen must be an instance of wx.Pen") |
| 1268 |
self._tickPen = pen |
| 1269 |
|
| 1270 |
@property |
| 1271 |
def tickLength(self): |
| 1272 |
"""The length of the tick marks on an axis. |
| 1273 |
|
| 1274 |
:getter: Returns the length of the tick marks. |
| 1275 |
:setter: Sets the length of the tick marks. |
| 1276 |
:type: tuple of (xlength, ylength): int or float |
| 1277 |
:raise: `TypeError` when setting a value that is not an int or float. |
| 1278 |
""" |
| 1279 |
return self._tickLength |
| 1280 |
|
| 1281 |
@tickLength.setter |
| 1282 |
def tickLength(self, length): |
| 1283 |
"""Set the length of the tick marks on an axis. |
| 1284 |
|
| 1285 |
Args: |
| 1286 |
length (tuple of (xlength, ylength)): The length of the tick marks. |
| 1287 |
|
| 1288 |
Raises: |
| 1289 |
TypeError: If `length` is not a 2-tuple of ints or floats. |
| 1290 |
""" |
| 1291 |
if not isinstance(length, (tuple, list)): |
| 1292 |
raise TypeError("`length` must be a 2-tuple of ints or floats") |
| 1293 |
self._tickLength = length |
| 1294 |
|
| 1295 |
@property |
| 1296 |
def tickLengthScale(self): |
| 1297 |
"""Scale tick length for hires antialiased mode and printing.""" |
| 1298 |
return ( |
| 1299 |
3 * self.printerScale * self._tickLength[0] * self._pointSize[0], |
| 1300 |
3 * self.printerScale * self._tickLength[1] * self._pointSize[1], |
| 1301 |
) |
| 1302 |
|
| 1303 |
# SaveFile |
| 1304 |
def SaveFile(self, fileName=""): |
| 1305 |
"""Save the file to the type specified in the extension. |
| 1306 |
|
| 1307 |
If no file name is specified provide a dialog box. Return True if successful, |
| 1308 |
False otherwise. |
| 1309 |
|
| 1310 |
.bmp Save a Windows bitmap file. |
| 1311 |
.xbm Save an X bitmap file. |
| 1312 |
.xpm Save an XPM bitmap file. |
| 1313 |
.png Save a Portable Network Graphics file. |
| 1314 |
.jpg Save a Joint Photographic Experts Group file. |
| 1315 |
""" |
| 1316 |
extensions = { |
| 1317 |
"bmp": wx.BITMAP_TYPE_BMP, # Save a Windows bitmap file. |
| 1318 |
"xbm": wx.BITMAP_TYPE_XBM, # Save an X bitmap file. |
| 1319 |
"xpm": wx.BITMAP_TYPE_XPM, # Save an XPM bitmap file. |
| 1320 |
"jpg": wx.BITMAP_TYPE_JPEG, # Save a JPG file. |
| 1321 |
"png": wx.BITMAP_TYPE_PNG, # Save a PNG file. |
| 1322 |
} |
| 1323 |
|
| 1324 |
fType = _string.lower(fileName[-3:]) |
| 1325 |
dlg1 = None |
| 1326 |
while fType not in extensions: |
| 1327 |
if dlg1: # FileDialog exists: Check for extension |
| 1328 |
dlg2 = wx.MessageDialog( |
| 1329 |
self, |
| 1330 |
"File name extension\nmust be one of\nbmp, xbm, xpm, png, or jpg", |
| 1331 |
"File Name Error", |
| 1332 |
wx.OK | wx.ICON_ERROR, |
| 1333 |
) |
| 1334 |
try: |
| 1335 |
dlg2.ShowModal() |
| 1336 |
finally: |
| 1337 |
dlg2.Destroy() |
| 1338 |
else: # FileDialog doesn't exist: just check one |
| 1339 |
dlg1 = wx.FileDialog( |
| 1340 |
self, |
| 1341 |
"Choose a file with extension bmp, gif, xbm, xpm, png, or jpg", |
| 1342 |
".", |
| 1343 |
"", |
| 1344 |
"BMP files (*.bmp)|*.bmp|XBM files (*.xbm)|*.xbm|XPM file " |
| 1345 |
"(*.xpm)|*.xpm|PNG files (*.png)|*.png|JPG files (*.jpg)|*.jpg", |
| 1346 |
wx.SAVE | wx.OVERWRITE_PROMPT, |
| 1347 |
) |
| 1348 |
|
| 1349 |
if dlg1.ShowModal() == wx.ID_OK: |
| 1350 |
fileName = dlg1.GetPath() |
| 1351 |
fType = _string.lower(fileName[-3:]) |
| 1352 |
else: # exit without saving |
| 1353 |
dlg1.Destroy() |
| 1354 |
return False |
| 1355 |
|
| 1356 |
if dlg1: |
| 1357 |
dlg1.Destroy() |
| 1358 |
|
| 1359 |
# Save Bitmap |
| 1360 |
return self._Buffer.SaveFile(fileName, extensions[fType]) |
| 1361 |
|
| 1362 |
@property |
| 1363 |
def print_data(self): |
| 1364 |
"""Get the print data for the print dialog. |
| 1365 |
|
| 1366 |
Returns: |
| 1367 |
wx.PrintData: The print data for the print dialog. |
| 1368 |
""" |
| 1369 |
if not self._print_data: |
| 1370 |
self._print_data = wx.PrintData() |
| 1371 |
self._print_data.SetPaperId(wx.PAPER_LETTER) |
| 1372 |
self._print_data.SetOrientation(wx.LANDSCAPE) |
| 1373 |
return self._print_data |
| 1374 |
|
| 1375 |
@property |
| 1376 |
def pageSetupData(self): |
| 1377 |
"""Get the page setup data for the print dialog. |
| 1378 |
|
| 1379 |
Returns: |
| 1380 |
wx.PageSetupDialogData: The page setup data for the print dialog. |
| 1381 |
""" |
| 1382 |
if not self._pageSetupData: |
| 1383 |
self._pageSetupData = wx.PageSetupDialogData() |
| 1384 |
self._pageSetupData.SetMarginBottomRight((25, 25)) |
| 1385 |
self._pageSetupData.SetMarginTopLeft((25, 25)) |
| 1386 |
self._pageSetupData.SetPrintData(self.print_data) |
| 1387 |
return self._pageSetupData |
| 1388 |
|
| 1389 |
def PageSetup(self): |
| 1390 |
"""Bring up the page setup dialog.""" |
| 1391 |
data = self.pageSetupData |
| 1392 |
data.SetPrintData(self.print_data) |
| 1393 |
dlg = wx.PageSetupDialog(self.parent, data) |
| 1394 |
try: |
| 1395 |
if dlg.ShowModal() == wx.ID_OK: |
| 1396 |
data = dlg.GetPageSetupData() # returns wx.PageSetupDialogData |
| 1397 |
# updates page parameters from dialog |
| 1398 |
self.pageSetupData.SetMarginBottomRight(data.GetMarginBottomRight()) |
| 1399 |
self.pageSetupData.SetMarginTopLeft(data.GetMarginTopLeft()) |
| 1400 |
self.pageSetupData.SetPrintData(data.GetPrintData()) |
| 1401 |
self._print_data = wx.PrintData( |
| 1402 |
data.GetPrintData() |
| 1403 |
) # updates print_data |
| 1404 |
finally: |
| 1405 |
dlg.Destroy() |
| 1406 |
|
| 1407 |
def Printout(self, paper=None): |
| 1408 |
"""Print current plot. |
| 1409 |
|
| 1410 |
Args: |
| 1411 |
paper (int, optional): The paper size to use for printing. If None, |
| 1412 |
the default paper size is used. Defaults to None. |
| 1413 |
""" |
| 1414 |
if paper is not None: |
| 1415 |
self.print_data.SetPaperId(paper) |
| 1416 |
pdd = wx.PrintDialogData(self.print_data) |
| 1417 |
printer = wx.Printer(pdd) |
| 1418 |
out = PlotPrintout(self) |
| 1419 |
print_ok = printer.Print(self.parent, out) |
| 1420 |
if print_ok: |
| 1421 |
self._print_data = wx.PrintData(printer.GetPrintDialogData().GetPrintData()) |
| 1422 |
out.Destroy() |
| 1423 |
|
| 1424 |
def PrintPreview(self) -> None: |
| 1425 |
"""Print-preview current plot.""" |
| 1426 |
printout = PlotPrintout(self) |
| 1427 |
printout2 = PlotPrintout(self) |
| 1428 |
self.preview = wx.PrintPreview(printout, printout2, self.print_data) |
| 1429 |
if not self.preview.Ok(): |
| 1430 |
wx.MessageDialog( |
| 1431 |
self, |
| 1432 |
"Print Preview failed.\nCheck that default printer is configured\n", |
| 1433 |
"Print error", |
| 1434 |
wx.OK | wx.CENTRE, |
| 1435 |
).ShowModal() |
| 1436 |
self.preview.SetZoom(40) |
| 1437 |
# search up tree to find frame instance |
| 1438 |
frameInst = self |
| 1439 |
while not isinstance(frameInst, wx.Frame): |
| 1440 |
frameInst = frameInst.GetParent() |
| 1441 |
frame = wx.PreviewFrame(self.preview, frameInst, "Preview") |
| 1442 |
frame.Initialize() |
| 1443 |
frame.SetPosition(self.GetPosition()) |
| 1444 |
frame.SetSize((600, 550)) |
| 1445 |
frame.Centre(wx.BOTH) |
| 1446 |
frame.Show(True) |
| 1447 |
|
| 1448 |
def setLogScale(self, logscale): |
| 1449 |
"""Set the log scale for the x and y axes. |
| 1450 |
|
| 1451 |
Args: |
| 1452 |
logscale (tuple): A tuple of two booleans (x_log, y_log) indicating |
| 1453 |
whether the x-axis and y-axis should be in log scale, respectively. |
| 1454 |
|
| 1455 |
Raises: |
| 1456 |
TypeError: If logscale is not a tuple of two booleans. |
| 1457 |
""" |
| 1458 |
if not isinstance(logscale, tuple): |
| 1459 |
raise TypeError("logscale must be a tuple of bools, e.g. (False, False)") |
| 1460 |
if self.last_draw is not None: |
| 1461 |
graphics, xAxis, yAxis = self.last_draw |
| 1462 |
graphics.setLogScale(logscale) |
| 1463 |
self.last_draw = (graphics, None, None) |
| 1464 |
self.SetXSpec("min") |
| 1465 |
self.SetYSpec("min") |
| 1466 |
self._logscale = logscale |
| 1467 |
|
| 1468 |
def getLogScale(self): |
| 1469 |
"""Return the current log scale setting as a tuple (x_log, y_log). |
| 1470 |
|
| 1471 |
Returns: |
| 1472 |
tuple: A tuple containing two boolean values indicating whether the |
| 1473 |
x-axis and y-axis are in log scale. |
| 1474 |
""" |
| 1475 |
return self._logscale |
| 1476 |
|
| 1477 |
def SetFontSizeAxis(self, point=10): |
| 1478 |
"""Set the tick and axis label font size (default is 10 point).""" |
| 1479 |
self._fontSizeAxis = point |
| 1480 |
|
| 1481 |
def GetFontSizeAxis(self): |
| 1482 |
"""Get current tick and axis label font size in points.""" |
| 1483 |
return self._fontSizeAxis |
| 1484 |
|
| 1485 |
def SetFontSizeTitle(self, point=15): |
| 1486 |
"""Set Title font size (default is 15 point).""" |
| 1487 |
self._fontSizeTitle = point |
| 1488 |
|
| 1489 |
def GetFontSizeTitle(self): |
| 1490 |
"""Get current Title font size in points.""" |
| 1491 |
return self._fontSizeTitle |
| 1492 |
|
| 1493 |
def SetFontSizeLegend(self, point=7): |
| 1494 |
"""Set Legend font size (default is 7 point).""" |
| 1495 |
self._fontSizeLegend = point |
| 1496 |
|
| 1497 |
def GetFontSizeLegend(self): |
| 1498 |
"""Get current Legend font size in points.""" |
| 1499 |
return self._fontSizeLegend |
| 1500 |
|
| 1501 |
def SetShowScrollbars(self, value): |
| 1502 |
"""Set True to show scrollbars.""" |
| 1503 |
if value not in [True, False]: |
| 1504 |
raise TypeError("Value should be True or False") |
| 1505 |
if value == self.GetShowScrollbars(): |
| 1506 |
return |
| 1507 |
self.sb_vert.Show(value) |
| 1508 |
self.sb_hor.Show(value) |
| 1509 |
wx.CallAfter(self.Layout) |
| 1510 |
|
| 1511 |
def GetShowScrollbars(self): |
| 1512 |
"""Set True to show scrollbars.""" |
| 1513 |
return self.sb_vert.IsShown() |
| 1514 |
|
| 1515 |
def SetUseScientificNotation(self, useScientificNotation): |
| 1516 |
"""Set True to use scientific notation for axis labels. |
| 1517 |
|
| 1518 |
Args: |
| 1519 |
useScientificNotation (bool): True to use scientific notation, |
| 1520 |
False otherwise. |
| 1521 |
""" |
| 1522 |
self._useScientificNotation = useScientificNotation |
| 1523 |
|
| 1524 |
def GetUseScientificNotation(self): |
| 1525 |
"""Return True if scientific notation is used for axis labels. |
| 1526 |
|
| 1527 |
Returns: |
| 1528 |
bool: True if scientific notation is used, False otherwise. |
| 1529 |
""" |
| 1530 |
return self._useScientificNotation |
| 1531 |
|
| 1532 |
def SetEnableAntiAliasing(self, enableAntiAliasing): |
| 1533 |
"""Set True to enable anti-aliasing. |
| 1534 |
|
| 1535 |
Args: |
| 1536 |
enableAntiAliasing (bool): True to enable anti-aliasing, False to |
| 1537 |
disable. |
| 1538 |
""" |
| 1539 |
self._antiAliasingEnabled = enableAntiAliasing |
| 1540 |
self.Redraw() |
| 1541 |
|
| 1542 |
def GetEnableAntiAliasing(self) -> bool: |
| 1543 |
"""Return True if anti-aliasing is enabled. |
| 1544 |
|
| 1545 |
Returns: |
| 1546 |
bool: True if anti-aliasing is enabled, False otherwise. |
| 1547 |
""" |
| 1548 |
return self._antiAliasingEnabled |
| 1549 |
|
| 1550 |
def SetEnableHiRes(self, enableHiRes): |
| 1551 |
"""Enable or disable high-resolution mode when using anti-aliasing. |
| 1552 |
|
| 1553 |
Args: |
| 1554 |
enableHiRes (bool): True to enable high-resolution mode, False to |
| 1555 |
disable. |
| 1556 |
""" |
| 1557 |
self._hiResEnabled = enableHiRes |
| 1558 |
self.Redraw() |
| 1559 |
|
| 1560 |
def GetEnableHiRes(self): |
| 1561 |
"""Return True if high-resolution mode is enabled. |
| 1562 |
|
| 1563 |
Returns: |
| 1564 |
bool: True if high-resolution mode is enabled, False otherwise. |
| 1565 |
""" |
| 1566 |
return self._hiResEnabled |
| 1567 |
|
| 1568 |
def SetEnableDrag(self, value: bool): |
| 1569 |
"""Enable or disable drag. |
| 1570 |
|
| 1571 |
Args: |
| 1572 |
value (bool): True to enable dragging, False to disable. |
| 1573 |
""" |
| 1574 |
if not isinstance(value, bool): |
| 1575 |
raise TypeError( |
| 1576 |
f"value should be a bool value, not {value.__class__.__name__}: {value}" |
| 1577 |
) |
| 1578 |
if value: |
| 1579 |
if self.GetEnableZoom(): |
| 1580 |
self.SetEnableZoom(False) |
| 1581 |
self.SetCursor(self.HandCursor) |
| 1582 |
else: |
| 1583 |
self.SetCursor(wx.CROSS_CURSOR) |
| 1584 |
self._dragEnabled = value |
| 1585 |
|
| 1586 |
def GetEnableDrag(self) -> bool: |
| 1587 |
"""Return True if the dragging is enabled. |
| 1588 |
|
| 1589 |
Returns: |
| 1590 |
bool: True if dragging is enabled, False otherwise. |
| 1591 |
""" |
| 1592 |
return self._dragEnabled |
| 1593 |
|
| 1594 |
def SetEnableZoom(self, value): |
| 1595 |
"""Set True to enable zooming.""" |
| 1596 |
if not isinstance(value, bool): |
| 1597 |
raise TypeError( |
| 1598 |
f"value should be a bool value, not {value.__class__.__name__}: {value}" |
| 1599 |
) |
| 1600 |
if value: |
| 1601 |
if self.GetEnableDrag(): |
| 1602 |
self.SetEnableDrag(False) |
| 1603 |
self.SetCursor(self.MagCursor) |
| 1604 |
else: |
| 1605 |
self.SetCursor(wx.CROSS_CURSOR) |
| 1606 |
self._zoomEnabled = value |
| 1607 |
|
| 1608 |
def GetEnableZoom(self): |
| 1609 |
"""True if zooming enabled.""" |
| 1610 |
return self._zoomEnabled |
| 1611 |
|
| 1612 |
def SetEnableGrid(self, value): |
| 1613 |
"""Set True, 'Horizontal' or 'Vertical' to enable grid.""" |
| 1614 |
if value not in [True, False, "Horizontal", "Vertical"]: |
| 1615 |
raise TypeError("Value should be True, False, Horizontal or Vertical") |
| 1616 |
self._gridEnabled = value |
| 1617 |
self.Redraw() |
| 1618 |
|
| 1619 |
def GetEnableGrid(self): |
| 1620 |
"""True if grid enabled.""" |
| 1621 |
return self._gridEnabled |
| 1622 |
|
| 1623 |
def SetEnableCenterLines(self, value): |
| 1624 |
"""Set True, 'Horizontal' or 'Vertical' to enable center line(s).""" |
| 1625 |
if value not in [True, False, "Horizontal", "Vertical"]: |
| 1626 |
raise TypeError("Value should be True, False, Horizontal or Vertical") |
| 1627 |
self._centerLinesEnabled = value |
| 1628 |
self.Redraw() |
| 1629 |
|
| 1630 |
def GetEnableCenterLines(self): |
| 1631 |
"""True if grid enabled.""" |
| 1632 |
return self._centerLinesEnabled |
| 1633 |
|
| 1634 |
def SetEnableDiagonals(self, value): |
| 1635 |
"""Set enable diagonals. |
| 1636 |
|
| 1637 |
Set True, 'Bottomleft-Topright' or 'Bottomright-Topleft' to enable |
| 1638 |
center line(s). |
| 1639 |
|
| 1640 |
Args: |
| 1641 |
value (bool | str): True to enable diagonals, False to disable, |
| 1642 |
or one of the strings of ['Bottomleft-Topright', 'Bottomright-Topleft'] |
| 1643 |
to indicate the diagonal direction. |
| 1644 |
|
| 1645 |
Raises: |
| 1646 |
TypeError: If value is not one of the expected types. |
| 1647 |
""" |
| 1648 |
if value not in [True, False, "Bottomleft-Topright", "Bottomright-Topleft"]: |
| 1649 |
raise TypeError( |
| 1650 |
"Value should be True, False, Bottomleft-Topright " |
| 1651 |
"or Bottomright-Topleft" |
| 1652 |
) |
| 1653 |
self._diagonalsEnabled = value |
| 1654 |
self.Redraw() |
| 1655 |
|
| 1656 |
def GetEnableDiagonals(self): |
| 1657 |
"""True if grid enabled.""" |
| 1658 |
return self._diagonalsEnabled |
| 1659 |
|
| 1660 |
def SetEnableLegend(self, value): |
| 1661 |
"""Set True to enable legend.""" |
| 1662 |
if value not in [True, False]: |
| 1663 |
raise TypeError("Value should be True or False") |
| 1664 |
self._legendEnabled = value |
| 1665 |
self.Redraw() |
| 1666 |
|
| 1667 |
def GetEnableLegend(self): |
| 1668 |
"""True if Legend enabled.""" |
| 1669 |
return self._legendEnabled |
| 1670 |
|
| 1671 |
def SetEnableTitle(self, value): |
| 1672 |
"""Set True to enable title.""" |
| 1673 |
if value not in [True, False]: |
| 1674 |
raise TypeError("Value should be True or False") |
| 1675 |
self._titleEnabled = value |
| 1676 |
self.Redraw() |
| 1677 |
|
| 1678 |
def GetEnableTitle(self): |
| 1679 |
"""True if title enabled.""" |
| 1680 |
return self._titleEnabled |
| 1681 |
|
| 1682 |
def SetEnablePointLabel(self, value): |
| 1683 |
"""Set True to enable pointLabel.""" |
| 1684 |
if value not in [True, False]: |
| 1685 |
raise TypeError("Value should be True or False") |
| 1686 |
self._pointLabelEnabled = value |
| 1687 |
self.Redraw() # will erase existing pointLabel if present |
| 1688 |
self.last_PointLabel = None |
| 1689 |
|
| 1690 |
def GetEnablePointLabel(self): |
| 1691 |
"""True if pointLabel enabled.""" |
| 1692 |
return self._pointLabelEnabled |
| 1693 |
|
| 1694 |
@property |
| 1695 |
def enableTicks(self): |
| 1696 |
"""The current enableTicks value. |
| 1697 |
|
| 1698 |
:getter: Returns the value of enableTicks. |
| 1699 |
:setter: Sets the value of enableTicks. |
| 1700 |
:type: bool, 2-tuple of bool, or 4-tuple of bool |
| 1701 |
:raises: `TypeError` if setting an invalid value. |
| 1702 |
:raises: `ValueError` if the tuple has incorrect length. |
| 1703 |
|
| 1704 |
If bool, enable or disable all ticks |
| 1705 |
|
| 1706 |
If 2-tuple, enable or disable the bottom or left ticks: |
| 1707 |
``(bottom, left)`` |
| 1708 |
|
| 1709 |
If 4-tuple, enable or disable each tick side individually: |
| 1710 |
``(bottom, left, top, right)`` |
| 1711 |
""" |
| 1712 |
return self._ticksEnabled |
| 1713 |
|
| 1714 |
@enableTicks.setter |
| 1715 |
def enableTicks(self, value): |
| 1716 |
self._ticksEnabled = set_display_side(value) |
| 1717 |
self.Redraw() |
| 1718 |
|
| 1719 |
def SetPointLabelFunc(self, func): |
| 1720 |
"""Set the function with custom code for pointLabel drawing. |
| 1721 |
|
| 1722 |
The function should take a single argument, which is the |
| 1723 |
wx.GraphicsContext, and a point as arguments. The function |
| 1724 |
should draw the point label at the specified point. |
| 1725 |
|
| 1726 |
Args: |
| 1727 |
func (callable): A function that takes a wx.GraphicsContext and |
| 1728 |
a point as arguments and draws the point label. |
| 1729 |
""" |
| 1730 |
self._pointLabelFunc = func |
| 1731 |
|
| 1732 |
def GetPointLabelFunc(self): |
| 1733 |
"""Return pointLabel Drawing Function.""" |
| 1734 |
return self._pointLabelFunc |
| 1735 |
|
| 1736 |
def Reset(self): |
| 1737 |
"""Unzoom the plot.""" |
| 1738 |
self.last_PointLabel = None # reset pointLabel |
| 1739 |
if self.last_draw is not None: |
| 1740 |
self._Draw(self.last_draw[0]) |
| 1741 |
|
| 1742 |
def ScrollRight(self, units): |
| 1743 |
"""Move view right number of axis units.""" |
| 1744 |
self.last_PointLabel = None # reset pointLabel |
| 1745 |
if self.last_draw is not None: |
| 1746 |
graphics, xAxis, yAxis = self.last_draw |
| 1747 |
xAxis = (xAxis[0] + units, xAxis[1] + units) |
| 1748 |
self._Draw(graphics, xAxis, yAxis) |
| 1749 |
|
| 1750 |
def ScrollUp(self, units): |
| 1751 |
"""Move view up number of axis units.""" |
| 1752 |
self.last_PointLabel = None # reset pointLabel |
| 1753 |
if self.last_draw is not None: |
| 1754 |
graphics, xAxis, yAxis = self.last_draw |
| 1755 |
yAxis = (yAxis[0] + units, yAxis[1] + units) |
| 1756 |
self._Draw(graphics, xAxis, yAxis) |
| 1757 |
|
| 1758 |
def GetXY(self, event): |
| 1759 |
"""Wrapper around _getXY, which handles log scales.""" |
| 1760 |
x, y = self._getXY(event) |
| 1761 |
if self.getLogScale()[0]: |
| 1762 |
x = np.power(10, x) |
| 1763 |
if self.getLogScale()[1]: |
| 1764 |
y = np.power(10, y) |
| 1765 |
return x, y |
| 1766 |
|
| 1767 |
def _getXY(self, event): |
| 1768 |
"""Take a mouse event and returns the XY user axis values.""" |
| 1769 |
x, y = self.PositionScreenToUser(event.GetPosition()) |
| 1770 |
return x, y |
| 1771 |
|
| 1772 |
def PositionUserToScreen(self, pntXY): |
| 1773 |
"""Convert User position to Screen Coordinates.""" |
| 1774 |
userPos = np.array(pntXY) |
| 1775 |
x, y = userPos * self._pointScale + self._pointShift |
| 1776 |
return x, y |
| 1777 |
|
| 1778 |
def PositionScreenToUser(self, pntXY): |
| 1779 |
"""Convert Screen position to User Coordinates.""" |
| 1780 |
screenPos = np.array(pntXY) |
| 1781 |
x, y = (screenPos - self._pointShift) / self._pointScale |
| 1782 |
return x, y |
| 1783 |
|
| 1784 |
def SetXSpec(self, type_="auto"): |
| 1785 |
"""Set the X axis type. |
| 1786 |
|
| 1787 |
xSpec- defines x axis type. Can be 'none', 'min' or 'auto' |
| 1788 |
|
| 1789 |
where: |
| 1790 |
'none' - shows no axis or tick mark values |
| 1791 |
'min' - shows min bounding box values |
| 1792 |
'auto' - rounds axis range to sensible values |
| 1793 |
<number> - like 'min', but with <number> tick marks |
| 1794 |
""" |
| 1795 |
self._xSpec = type_ |
| 1796 |
|
| 1797 |
def SetYSpec(self, type_="auto"): |
| 1798 |
"""Set the Y axis type. |
| 1799 |
|
| 1800 |
ySpec- defines x axis type. Can be 'none', 'min' or 'auto'. |
| 1801 |
|
| 1802 |
where: |
| 1803 |
'none' - shows no axis or tick mark values |
| 1804 |
'min' - shows min bounding box values |
| 1805 |
'auto' - rounds axis range to sensible values |
| 1806 |
<number> - like 'min', but with <number> tick marks |
| 1807 |
""" |
| 1808 |
self._ySpec = type_ |
| 1809 |
|
| 1810 |
def GetXSpec(self): |
| 1811 |
"""Return current XSpec for axis.""" |
| 1812 |
return self._xSpec |
| 1813 |
|
| 1814 |
def GetYSpec(self): |
| 1815 |
"""Return current YSpec for axis.""" |
| 1816 |
return self._ySpec |
| 1817 |
|
| 1818 |
@property |
| 1819 |
def xSpec(self): |
| 1820 |
"""Define the X axis type. |
| 1821 |
|
| 1822 |
Default is 'auto'. |
| 1823 |
|
| 1824 |
:getter: Returns the value of xSpec. |
| 1825 |
:setter: Sets the value of xSpec. |
| 1826 |
:type: str, int, or length-2 sequence of floats |
| 1827 |
:raises: `TypeError` if setting an invalid value. |
| 1828 |
|
| 1829 |
Valid strings: |
| 1830 |
+ 'none' - shows no axis or tick mark values |
| 1831 |
+ 'min' - shows min bounding box values |
| 1832 |
+ 'auto' - rounds axis range to sensible values |
| 1833 |
|
| 1834 |
Other valid values: |
| 1835 |
+ <number> - like 'min', but with <number> tick marks |
| 1836 |
+ list or tuple: a list of (min, max) values. Must be length 2. |
| 1837 |
|
| 1838 |
.. seealso:: |
| 1839 |
:attr:`~wx.lib.plot.plotcanvas.PlotCanvas.ySpec` |
| 1840 |
""" |
| 1841 |
return self._xSpec |
| 1842 |
|
| 1843 |
@xSpec.setter |
| 1844 |
def xSpec(self, value): |
| 1845 |
"""Set the X axis type. |
| 1846 |
|
| 1847 |
Args: |
| 1848 |
value (None | str, int, float, list, tuple): Default is 'auto'. |
| 1849 |
Valid values are: |
| 1850 |
- 'none' - shows no axis or tick mark values |
| 1851 |
- 'min' - shows min bounding box values |
| 1852 |
- 'auto' - rounds axis range to sensible values |
| 1853 |
- <number> - like 'min', but with <number> tick marks |
| 1854 |
- list or tuple: a list of (min, max) values. Must be length 2. |
| 1855 |
|
| 1856 |
Raises: |
| 1857 |
TypeError: If value is not one of the valid types or formats. |
| 1858 |
""" |
| 1859 |
ok_values = ("none", "min", "auto") |
| 1860 |
if ( |
| 1861 |
value not in ok_values |
| 1862 |
and not isinstance(value, (int, float)) |
| 1863 |
and not isinstance(value, (list, tuple)) |
| 1864 |
and len(value != 2) |
| 1865 |
): |
| 1866 |
err_str = ( |
| 1867 |
"xSpec must be 'none', 'min', 'auto', " |
| 1868 |
"a number, or sequence of numbers (length 2)" |
| 1869 |
) |
| 1870 |
raise TypeError(err_str) |
| 1871 |
self._xSpec = value |
| 1872 |
|
| 1873 |
@property |
| 1874 |
def ySpec(self): |
| 1875 |
"""Define the Y axis type. |
| 1876 |
|
| 1877 |
Default is 'auto'. |
| 1878 |
|
| 1879 |
:getter: Returns the value of xSpec. |
| 1880 |
:setter: Sets the value of xSpec. |
| 1881 |
:type: str, int, or length-2 sequence of floats |
| 1882 |
:raises: `TypeError` if setting an invalid value. |
| 1883 |
|
| 1884 |
Valid strings: |
| 1885 |
+ 'none' - shows no axis or tick mark values |
| 1886 |
+ 'min' - shows min bounding box values |
| 1887 |
+ 'auto' - rounds axis range to sensible values |
| 1888 |
|
| 1889 |
Other valid values: |
| 1890 |
+ <number> - like 'min', but with <number> tick marks |
| 1891 |
+ list or tuple: a list of (min, max) values. Must be length 2. |
| 1892 |
|
| 1893 |
.. seealso:: |
| 1894 |
:attr:`~wx.lib.plot.plotcanvas.PlotCanvas.xSpec` |
| 1895 |
""" |
| 1896 |
return self._ySpec |
| 1897 |
|
| 1898 |
@ySpec.setter |
| 1899 |
def ySpec(self, value): |
| 1900 |
"""Set the Y axis type. |
| 1901 |
|
| 1902 |
Args: |
| 1903 |
value (None | str, int, float, list, tuple): Default is 'auto'. |
| 1904 |
Valid values are: |
| 1905 |
|
| 1906 |
- 'none' - shows no axis or tick mark values |
| 1907 |
- 'min' - shows min bounding box values |
| 1908 |
- 'auto' - rounds axis range to sensible values |
| 1909 |
- <number> - like 'min', but with <number> tick marks |
| 1910 |
- list or tuple: a list of (min, max) values. Must be length 2. |
| 1911 |
|
| 1912 |
Raises: |
| 1913 |
TypeError: If value is not one of the valid types or formats. |
| 1914 |
""" |
| 1915 |
ok_values = ("none", "min", "auto") |
| 1916 |
if ( |
| 1917 |
value not in ok_values |
| 1918 |
and not isinstance(value, (int, float)) |
| 1919 |
and not isinstance(value, (list, tuple)) |
| 1920 |
and len(value != 2) |
| 1921 |
): |
| 1922 |
err_str = ( |
| 1923 |
"ySpec must be 'none', 'min', 'auto', " |
| 1924 |
"a number, or sequence of numbers (length 2)" |
| 1925 |
) |
| 1926 |
raise TypeError(err_str) |
| 1927 |
self._ySpec = value |
| 1928 |
|
| 1929 |
def GetXMaxRange(self): |
| 1930 |
"""Return (minX, maxX) x-axis range for displayed graph. |
| 1931 |
|
| 1932 |
Returns: |
| 1933 |
tuple: A tuple containing the minimum and maximum x-axis values |
| 1934 |
for the currently displayed portion of the graph. |
| 1935 |
""" |
| 1936 |
xAxis = self._getXMaxRange() |
| 1937 |
if self.getLogScale()[0]: |
| 1938 |
xAxis = np.power(10, xAxis) |
| 1939 |
return xAxis |
| 1940 |
|
| 1941 |
def _getXMaxRange(self): |
| 1942 |
"""Return (minX, maxX) x-axis range for displayed graph. |
| 1943 |
|
| 1944 |
Returns: |
| 1945 |
tuple: A tuple containing the minimum and maximum x-axis values |
| 1946 |
for the currently displayed portion of the graph. |
| 1947 |
""" |
| 1948 |
graphics = self.last_draw[0] |
| 1949 |
p1, p2 = graphics.boundingBox() # min, max points of graphics |
| 1950 |
return self._axisInterval(self._xSpec, p1[0], p2[0]) # in user units |
| 1951 |
|
| 1952 |
def GetYMaxRange(self): |
| 1953 |
"""Return (minY, maxY) y-axis range for displayed graph. |
| 1954 |
|
| 1955 |
Returns: |
| 1956 |
tuple: A tuple containing the minimum and maximum y-axis values |
| 1957 |
for the currently displayed portion of the graph. |
| 1958 |
""" |
| 1959 |
yAxis = self._getYMaxRange() |
| 1960 |
if self.getLogScale()[1]: |
| 1961 |
yAxis = np.power(10, yAxis) |
| 1962 |
return yAxis |
| 1963 |
|
| 1964 |
def _getYMaxRange(self): |
| 1965 |
"""Return (minY, maxY) y-axis range for displayed graph. |
| 1966 |
|
| 1967 |
Returns: |
| 1968 |
tuple: A tuple containing the minimum and maximum y-axis values |
| 1969 |
for the currently displayed portion of the graph. |
| 1970 |
""" |
| 1971 |
graphics = self.last_draw[0] |
| 1972 |
p1, p2 = graphics.boundingBox() # min, max points of graphics |
| 1973 |
return self._axisInterval(self._ySpec, p1[1], p2[1]) |
| 1974 |
|
| 1975 |
def GetXCurrentRange(self): |
| 1976 |
"""Return (minX, maxX) x-axis for currently displayed portion of graph. |
| 1977 |
|
| 1978 |
Returns: |
| 1979 |
tuple: A tuple containing the minimum and maximum x-axis values |
| 1980 |
for the currently displayed portion of the graph. |
| 1981 |
""" |
| 1982 |
xAxis = self._getXCurrentRange() |
| 1983 |
if self.getLogScale()[0]: |
| 1984 |
xAxis = np.power(10, xAxis) |
| 1985 |
return xAxis |
| 1986 |
|
| 1987 |
def _getXCurrentRange(self): |
| 1988 |
"""Return (minX, maxX) x-axis for currently displayed portion of graph. |
| 1989 |
|
| 1990 |
Returns: |
| 1991 |
tuple: A tuple containing the minimum and maximum x-axis values |
| 1992 |
for the currently displayed portion of the graph. |
| 1993 |
""" |
| 1994 |
return self.last_draw[1] |
| 1995 |
|
| 1996 |
def GetYCurrentRange(self): |
| 1997 |
"""Return (minY, maxY) y-axis for currently displayed portion of graph. |
| 1998 |
|
| 1999 |
Returns: |
| 2000 |
tuple: A tuple containing the minimum and maximum y-axis values |
| 2001 |
for the currently displayed portion of the graph. |
| 2002 |
""" |
| 2003 |
yAxis = self._getYCurrentRange() |
| 2004 |
if self.getLogScale()[1]: |
| 2005 |
yAxis = np.power(10, yAxis) |
| 2006 |
return yAxis |
| 2007 |
|
| 2008 |
def _getYCurrentRange(self): |
| 2009 |
"""Return (minY, maxY) y-axis for currently displayed portion of graph. |
| 2010 |
|
| 2011 |
Returns: |
| 2012 |
tuple: A tuple containing the minimum and maximum y-axis values |
| 2013 |
for the currently displayed portion of the graph. |
| 2014 |
""" |
| 2015 |
return self.last_draw[2] |
| 2016 |
|
| 2017 |
def Draw(self, graphics, xAxis=None, yAxis=None, dc=None): |
| 2018 |
"""Wrapper around _Draw, which handles log axes. |
| 2019 |
|
| 2020 |
Args: |
| 2021 |
graphics (PlotGraphics): A PlotGraphics instance with list of |
| 2022 |
PolyXXX objects. |
| 2023 |
xAxis (tuple[int, int], optional): Tuple with (min, max) x-axis |
| 2024 |
range to view. If None, the x-axis is determined from the |
| 2025 |
graphics. |
| 2026 |
yAxis (tuple[int, int], optional): Same as xAxis, but for y-axis. |
| 2027 |
dc (wx.DC, optional): Optional drawing context. If it's None, the |
| 2028 |
offscreen buffer is used. |
| 2029 |
|
| 2030 |
Raises: |
| 2031 |
TypeError: If xAxis or yAxis is not None or a tuple of two numbers. |
| 2032 |
ValueError: If xAxis or yAxis has the same min and max value, which |
| 2033 |
would result in an invalid axis range. |
| 2034 |
""" |
| 2035 |
graphics.setLogScale(self.getLogScale()) |
| 2036 |
|
| 2037 |
# check Axis is either tuple or none |
| 2038 |
if xAxis is not None and not isinstance(xAxis, tuple): |
| 2039 |
raise TypeError( |
| 2040 |
f"xAxis should be None or (minX, maxX) not {xAxis.__class__.__name__}" |
| 2041 |
) |
| 2042 |
|
| 2043 |
if yAxis is not None and not isinstance(yAxis, tuple): |
| 2044 |
raise TypeError( |
| 2045 |
f"yAxis should be None or (minY, maxY) not {yAxis.__class__.__name__}" |
| 2046 |
) |
| 2047 |
|
| 2048 |
# check case for axis = (a,b) where a==b caused by improper zooms |
| 2049 |
if xAxis is not None: |
| 2050 |
if xAxis[0] == xAxis[1]: |
| 2051 |
return |
| 2052 |
if self.getLogScale()[0]: |
| 2053 |
xAxis = np.log10(xAxis) |
| 2054 |
if yAxis is not None: |
| 2055 |
if yAxis[0] == yAxis[1]: |
| 2056 |
return |
| 2057 |
if self.getLogScale()[1]: |
| 2058 |
yAxis = np.log10(yAxis) |
| 2059 |
self._Draw(graphics, xAxis, yAxis, dc) |
| 2060 |
|
| 2061 |
def _Draw(self, graphics, xAxis=None, yAxis=None, dc=None): |
| 2062 |
"""Draw objects in graphics with specified x and y axis. |
| 2063 |
|
| 2064 |
Args: |
| 2065 |
graphics (PlotGraphics): A PlotGraphics instance with list of |
| 2066 |
PolyXXX objects. |
| 2067 |
xAxis (tuple[int, int], optional): Tuple with (min, max) axis range |
| 2068 |
to view. |
| 2069 |
yAxis (tuple[int, int], optional): Same as xAxis. |
| 2070 |
dc (wx.DC, optional): Optional drawing context. If it's None, the |
| 2071 |
offscreen buffer is used. |
| 2072 |
""" |
| 2073 |
if dc is None: |
| 2074 |
# sets new dc and clears it |
| 2075 |
dc = wx.BufferedDC(wx.ClientDC(self.canvas), self._Buffer) |
| 2076 |
bbr = wx.Brush(self.GetBackgroundColour(), wx.BRUSHSTYLE_SOLID) |
| 2077 |
dc.SetBackground(bbr) |
| 2078 |
dc.SetBackgroundMode(wx.BRUSHSTYLE_SOLID) |
| 2079 |
dc.Clear() |
| 2080 |
if self._antiAliasingEnabled: |
| 2081 |
if not isinstance(dc, wx.GCDC): |
| 2082 |
try: |
| 2083 |
dc = wx.GCDC(dc) |
| 2084 |
except Exception: |
| 2085 |
pass |
| 2086 |
else: |
| 2087 |
if self._hiResEnabled: |
| 2088 |
dc.SetMapMode( |
| 2089 |
wx.MM_TWIPS |
| 2090 |
) # high precision - each logical unit is 1/20 of a point |
| 2091 |
self._pointSize = tuple( |
| 2092 |
1.0 / lscale for lscale in dc.GetLogicalScale() |
| 2093 |
) |
| 2094 |
self._setSize() |
| 2095 |
elif self._pointSize != (1.0, 1.0): |
| 2096 |
self._pointSize = (1.0, 1.0) |
| 2097 |
self._setSize() |
| 2098 |
self._fontScale = get_dc_font_scale(dc) |
| 2099 |
graphics._pointSize = self._pointSize |
| 2100 |
|
| 2101 |
dc.SetTextForeground(self.GetForegroundColour()) |
| 2102 |
dc.SetTextBackground(self.GetBackgroundColour()) |
| 2103 |
|
| 2104 |
# dc.Clear() |
| 2105 |
|
| 2106 |
# set font size for every thing but title and legend |
| 2107 |
dc.SetFont(self._getFont(self._fontSizeAxis)) |
| 2108 |
|
| 2109 |
# sizes axis to axis type, create lower left and upper right corners of plot |
| 2110 |
if xAxis is None or yAxis is None: |
| 2111 |
# One or both axis not specified in Draw |
| 2112 |
p1, p2 = graphics.boundingBox() # min, max points of graphics |
| 2113 |
if xAxis is None: |
| 2114 |
xAxis = self._axisInterval(self._xSpec, p1[0], p2[0]) # in user units |
| 2115 |
if yAxis is None: |
| 2116 |
yAxis = self._axisInterval(self._ySpec, p1[1], p2[1]) |
| 2117 |
# Adjust bounding box for axis spec |
| 2118 |
p1[0], p1[1] = ( |
| 2119 |
xAxis[0], |
| 2120 |
yAxis[0], |
| 2121 |
) # lower left corner user scale (xmin,ymin) |
| 2122 |
p2[0], p2[1] = ( |
| 2123 |
xAxis[1], |
| 2124 |
yAxis[1], |
| 2125 |
) # upper right corner user scale (xmax,ymax) |
| 2126 |
else: |
| 2127 |
# Both axis specified in Draw |
| 2128 |
p1 = np.array( |
| 2129 |
[xAxis[0], yAxis[0]] |
| 2130 |
) # lower left corner user scale (xmin,ymin) |
| 2131 |
p2 = np.array( |
| 2132 |
[xAxis[1], yAxis[1]] |
| 2133 |
) # upper right corner user scale (xmax,ymax) |
| 2134 |
|
| 2135 |
self.last_draw = ( |
| 2136 |
graphics, |
| 2137 |
np.array(xAxis), |
| 2138 |
np.array(yAxis), |
| 2139 |
) # saves most recient values |
| 2140 |
|
| 2141 |
# Get ticks and textExtents for axis if required |
| 2142 |
xticks = self._xticks(xAxis[0], xAxis[1]) if self._xSpec != "none" else None |
| 2143 |
# w h of x axis text last number on axis if `xticks`` else No text for ticks |
| 2144 |
xTextExtent = dc.GetTextExtent(xticks[-1][1]) if xticks else (0, 0) |
| 2145 |
yticks = self._yticks(yAxis[0], yAxis[1]) if self._ySpec != "none" else None |
| 2146 |
if yticks: |
| 2147 |
if self.getLogScale()[1]: |
| 2148 |
yTextExtent = dc.GetTextExtent("-2e-2") |
| 2149 |
else: |
| 2150 |
yTextExtentBottom = dc.GetTextExtent(yticks[0][1]) |
| 2151 |
yTextExtentTop = dc.GetTextExtent(yticks[-1][1]) |
| 2152 |
yTextExtent = ( |
| 2153 |
max(yTextExtentBottom[0], yTextExtentTop[0]), |
| 2154 |
max(yTextExtentBottom[1], yTextExtentTop[1]), |
| 2155 |
) |
| 2156 |
else: |
| 2157 |
yTextExtent = (0, 0) # No text for ticks |
| 2158 |
|
| 2159 |
# TextExtents for Title and Axis Labels |
| 2160 |
titleWH, xLabelWH, yLabelWH = self._titleLablesWH(dc, graphics) |
| 2161 |
|
| 2162 |
# TextExtents for Legend |
| 2163 |
legendBoxWH, legendSymExt, legendTextExt = self._legendWH(dc, graphics) |
| 2164 |
|
| 2165 |
# room around graph area |
| 2166 |
legend_inside = True |
| 2167 |
if legend_inside: |
| 2168 |
# Legend inside graph |
| 2169 |
x_offset = xTextExtent[0] |
| 2170 |
else: |
| 2171 |
# Legend outside graph |
| 2172 |
x_offset = max(xTextExtent[0], legendBoxWH[0]) |
| 2173 |
rhsW = ( |
| 2174 |
x_offset + 5 * self._pointSize[0] |
| 2175 |
) # use larger of number width or legend width |
| 2176 |
lhsW = yTextExtent[0] + yLabelWH[1] + 5 * self._pointSize[0] |
| 2177 |
bottomH = ( |
| 2178 |
max(xTextExtent[1], yTextExtent[1] / 2.0) |
| 2179 |
+ xLabelWH[1] |
| 2180 |
+ 2 * self._pointSize[1] |
| 2181 |
) |
| 2182 |
topH = yTextExtent[1] / 2.0 + titleWH[1] |
| 2183 |
textSize_scale = np.array( |
| 2184 |
[rhsW + lhsW, bottomH + topH] |
| 2185 |
) # make plot area smaller by text size |
| 2186 |
textSize_shift = np.array([lhsW, bottomH]) # shift plot area by this amount |
| 2187 |
|
| 2188 |
# draw title if requested |
| 2189 |
if self._titleEnabled: |
| 2190 |
dc.SetFont(self._getFont(self._fontSizeTitle)) |
| 2191 |
titlePos = ( |
| 2192 |
self.plotbox_origin[0] |
| 2193 |
+ lhsW |
| 2194 |
+ (self.plotbox_size[0] - lhsW - rhsW) / 2.0 |
| 2195 |
- titleWH[0] / 2.0, |
| 2196 |
self.plotbox_origin[1] - self.plotbox_size[1], |
| 2197 |
) |
| 2198 |
dc.DrawText(graphics.getTitle(), int(titlePos[0]), int(titlePos[1])) |
| 2199 |
|
| 2200 |
# draw label text |
| 2201 |
self._drawAxesLabels( |
| 2202 |
dc, graphics, lhsW, rhsW, bottomH, topH, xLabelWH, yLabelWH |
| 2203 |
) |
| 2204 |
|
| 2205 |
# allow for scaling and shifting plotted points |
| 2206 |
scale = (self.plotbox_size - textSize_scale) / (p2 - p1) * np.array((1, -1)) |
| 2207 |
shift = -p1 * scale + self.plotbox_origin + textSize_shift * np.array((1, -1)) |
| 2208 |
self._pointScale = scale / self._pointSize # make available for mouse events |
| 2209 |
self._pointShift = shift / self._pointSize |
| 2210 |
|
| 2211 |
# Draw ticks |
| 2212 |
if self._ticksEnabled: |
| 2213 |
self._drawTicks(dc, p1, p2, scale, shift, xticks, yticks) |
| 2214 |
|
| 2215 |
self._drawAxes(dc, p1, p2, scale, shift, xticks, yticks) |
| 2216 |
|
| 2217 |
# draw legend makers and text (if outside) |
| 2218 |
if self._legendEnabled and not legend_inside: |
| 2219 |
self._drawLegend( |
| 2220 |
dc, graphics, rhsW, topH, legendBoxWH, legendSymExt, legendTextExt |
| 2221 |
) |
| 2222 |
|
| 2223 |
graphics.scaleAndShift(scale, shift) |
| 2224 |
graphics.setPrinterScale( |
| 2225 |
self.printerScale |
| 2226 |
) # thicken up lines and markers if printing |
| 2227 |
|
| 2228 |
# set clipping area so drawing does not occur outside axis box |
| 2229 |
ptx, pty, rectWidth, rectHeight = self._point2ClientCoord(p1, p2) |
| 2230 |
# allow graph to overlap axis lines by adding units to width and height |
| 2231 |
dc.SetClippingRegion( |
| 2232 |
int(ptx * self._pointSize[0]), |
| 2233 |
int(pty * self._pointSize[1]), |
| 2234 |
int(rectWidth * self._pointSize[0] + 2), |
| 2235 |
int(rectHeight * self._pointSize[1] + 1), |
| 2236 |
) |
| 2237 |
# Draw extras |
| 2238 |
self._drawExtras(dc, p1, p2, scale, shift) |
| 2239 |
# Draw the lines and markers |
| 2240 |
# start = _time.time() |
| 2241 |
graphics.draw(dc) |
| 2242 |
|
| 2243 |
# draw legend makers and text (if inside) so that it overlaps graphics |
| 2244 |
if self._legendEnabled and legend_inside: |
| 2245 |
rhsW += legendBoxWH[0] |
| 2246 |
self._drawLegend( |
| 2247 |
dc, graphics, rhsW, topH, legendBoxWH, legendSymExt, legendTextExt |
| 2248 |
) |
| 2249 |
|
| 2250 |
# print "entire graphics drawing took: %f second"%(_time.time() - start) |
| 2251 |
# remove the clipping region |
| 2252 |
dc.DestroyClippingRegion() |
| 2253 |
|
| 2254 |
self._adjustScrollbars() |
| 2255 |
if "gtk3" in wx.PlatformInfo: |
| 2256 |
self.Refresh() |
| 2257 |
|
| 2258 |
def Redraw(self, dc=None): |
| 2259 |
"""Redraw the existing plot. |
| 2260 |
|
| 2261 |
Args: |
| 2262 |
dc (wx.DC, optional): The device context to use for drawing. |
| 2263 |
If None, a new BufferedDC is created using the canvas. |
| 2264 |
""" |
| 2265 |
if self.last_draw is not None: |
| 2266 |
graphics, xAxis, yAxis = self.last_draw |
| 2267 |
self._Draw(graphics, xAxis, yAxis, dc) |
| 2268 |
|
| 2269 |
def Clear(self): |
| 2270 |
"""Erase the window.""" |
| 2271 |
self.last_PointLabel = None # reset pointLabel |
| 2272 |
dc = wx.BufferedDC(wx.ClientDC(self.canvas), self._Buffer) |
| 2273 |
bbr = wx.Brush(self.GetBackgroundColour(), wx.BRUSHSTYLE_SOLID) |
| 2274 |
dc.SetBackground(bbr) |
| 2275 |
dc.SetBackgroundMode(wx.BRUSHSTYLE_SOLID) |
| 2276 |
dc.Clear() |
| 2277 |
if self._antiAliasingEnabled: |
| 2278 |
with contextlib.suppress(Exception): |
| 2279 |
dc = wx.GCDC(dc) |
| 2280 |
dc.SetTextForeground(self.GetForegroundColour()) |
| 2281 |
dc.SetTextBackground(self.GetBackgroundColour()) |
| 2282 |
self.last_draw = None |
| 2283 |
if "gtk3" in wx.PlatformInfo: |
| 2284 |
self.Refresh() |
| 2285 |
self.Update() |
| 2286 |
|
| 2287 |
def Zoom(self, Center, Ratio): |
| 2288 |
"""Zoom on the plot. |
| 2289 |
|
| 2290 |
Args: |
| 2291 |
Center (tuple): The center point (x, y) in user coordinates to zoom around. |
| 2292 |
Ratio (tuple): The zoom ratio (x_ratio, y_ratio) to apply. |
| 2293 |
""" |
| 2294 |
self.last_PointLabel = None # reset maker |
| 2295 |
x, y = Center |
| 2296 |
if self.last_draw is not None: |
| 2297 |
(graphics, xAxis, yAxis) = self.last_draw |
| 2298 |
w = (xAxis[1] - xAxis[0]) * Ratio[0] |
| 2299 |
h = (yAxis[1] - yAxis[0]) * Ratio[1] |
| 2300 |
xAxis = (x - w / 2, x + w / 2) |
| 2301 |
yAxis = (y - h / 2, y + h / 2) |
| 2302 |
self._Draw(graphics, xAxis, yAxis) |
| 2303 |
|
| 2304 |
def GetClosestPoints(self, pntXY, pointScaled=True): |
| 2305 |
"""Get the closest points to pntXY on the graph. |
| 2306 |
|
| 2307 |
Return list with: |
| 2308 |
[curveNumber, legend, index of closest point, pointXY, scaledXY, distance] |
| 2309 |
list for each curve. |
| 2310 |
Returns [] if no curves are being plotted. |
| 2311 |
|
| 2312 |
x, y in user coords |
| 2313 |
if pointScaled == True based on screen coords |
| 2314 |
if pointScaled == False based on user coords |
| 2315 |
|
| 2316 |
Args: |
| 2317 |
pntXY (tuple): The point in user coordinates to find the closest |
| 2318 |
points to. |
| 2319 |
pointScaled (bool): If True, returns the closest points based on |
| 2320 |
screen coordinates. If False, returns based on user |
| 2321 |
coordinates. |
| 2322 |
|
| 2323 |
Returns: |
| 2324 |
list: A list of lists, each containing: |
| 2325 |
|
| 2326 |
[ |
| 2327 |
curveNumber, |
| 2328 |
legend, |
| 2329 |
index of closest point, |
| 2330 |
pointXY, |
| 2331 |
scaledXY, |
| 2332 |
distance |
| 2333 |
] |
| 2334 |
|
| 2335 |
for each curve. |
| 2336 |
""" |
| 2337 |
if self.last_draw is None: |
| 2338 |
# no graph available |
| 2339 |
return [] |
| 2340 |
graphics, xAxis, yAxis = self.last_draw |
| 2341 |
closest_points = [] |
| 2342 |
for curveNum, obj in enumerate(graphics): |
| 2343 |
# check there are points in the curve |
| 2344 |
if len(obj.points) == 0: |
| 2345 |
continue # go to next obj |
| 2346 |
# [curveNumber, legend, index of closest point, pointXY, scaledXY, distance] |
| 2347 |
cn = [curveNum, obj.getLegend(), *obj.getClosestPoint(pntXY, pointScaled)] |
| 2348 |
closest_points.append(cn) |
| 2349 |
return closest_points |
| 2350 |
|
| 2351 |
def GetClosestPoint(self, pntXY, pointScaled=True): |
| 2352 |
"""Get the closest point to pntXY on the graph. |
| 2353 |
|
| 2354 |
Return list with: |
| 2355 |
[curveNumber, legend, index of closest point, pointXY, scaledXY, distance] |
| 2356 |
list for only the closest curve. |
| 2357 |
Returns [] if no curves are being plotted. |
| 2358 |
|
| 2359 |
x, y in user coords |
| 2360 |
if pointScaled == True based on screen coords |
| 2361 |
if pointScaled == False based on user coords |
| 2362 |
|
| 2363 |
Args: |
| 2364 |
pntXY (tuple): The point in user coordinates to find the closest |
| 2365 |
point to. |
| 2366 |
pointScaled (bool): If True, returns the closest point based on |
| 2367 |
screen coordinates. If False, returns based on user |
| 2368 |
coordinates. |
| 2369 |
|
| 2370 |
Returns: |
| 2371 |
list: A list containing: |
| 2372 |
|
| 2373 |
[ |
| 2374 |
curveNumber, |
| 2375 |
legend, |
| 2376 |
index of closest point, |
| 2377 |
pointXY, |
| 2378 |
scaledXY, |
| 2379 |
distance |
| 2380 |
] |
| 2381 |
""" |
| 2382 |
# closest points on screen based on screen scaling (pointScaled= True) |
| 2383 |
# list [curveNumber, index, pointXY, scaledXY, distance] for each curve |
| 2384 |
closestPts = self.GetClosestPoints(pntXY, pointScaled) |
| 2385 |
if not closestPts: |
| 2386 |
return [] # no graph present |
| 2387 |
# find one with least distance |
| 2388 |
dists = [c[-1] for c in closestPts] |
| 2389 |
mdist = min(dists) # Min dist |
| 2390 |
i = dists.index(mdist) # index for min dist |
| 2391 |
return closestPts[i] # this is the closest point on closest curve |
| 2392 |
|
| 2393 |
GetClosetPoint = GetClosestPoint |
| 2394 |
|
| 2395 |
def UpdatePointLabel(self, mDataDict): |
| 2396 |
"""Update the pointLabel point on screen with data contained in mDataDict. |
| 2397 |
|
| 2398 |
mDataDict will be passed to your function set by |
| 2399 |
SetPointLabelFunc. It can contain anything you |
| 2400 |
want to display on the screen at the scaledXY point |
| 2401 |
you specify. |
| 2402 |
|
| 2403 |
This function can be called from parent window with onClick, |
| 2404 |
onMotion events etc. |
| 2405 |
|
| 2406 |
Args: |
| 2407 |
mDataDict (dict): A dictionary containing the data to be displayed. |
| 2408 |
""" |
| 2409 |
if self.last_PointLabel is not None: |
| 2410 |
# compare pointXY |
| 2411 |
if np.any(mDataDict["pointXY"] != self.last_PointLabel["pointXY"]): |
| 2412 |
# closest changed |
| 2413 |
self._drawPointLabel(self.last_PointLabel) # erase old |
| 2414 |
self._drawPointLabel(mDataDict) # plot new |
| 2415 |
else: |
| 2416 |
# just plot new with no erase |
| 2417 |
self._drawPointLabel(mDataDict) # plot new |
| 2418 |
# save for next erase |
| 2419 |
self.last_PointLabel = mDataDict |
| 2420 |
|
| 2421 |
# event handlers ********************************** |
| 2422 |
def OnMotion(self, event): |
| 2423 |
"""Handle mouse motion events. |
| 2424 |
|
| 2425 |
Args: |
| 2426 |
event (wx.Event): The event that triggered this method. |
| 2427 |
""" |
| 2428 |
if self._zoomEnabled and event.LeftIsDown(): |
| 2429 |
if self._hasDragged: |
| 2430 |
self._drawRubberBand(self._zoomCorner1, self._zoomCorner2) # remove old |
| 2431 |
else: |
| 2432 |
self._hasDragged = True |
| 2433 |
self._zoomCorner2[0], self._zoomCorner2[1] = self._getXY(event) |
| 2434 |
self._drawRubberBand(self._zoomCorner1, self._zoomCorner2) # add new |
| 2435 |
elif self._dragEnabled and event.LeftIsDown(): |
| 2436 |
coordinates = event.GetPosition() |
| 2437 |
newpos, oldpos = list( |
| 2438 |
map( |
| 2439 |
np.array, |
| 2440 |
list( |
| 2441 |
map( |
| 2442 |
self.PositionScreenToUser, |
| 2443 |
[coordinates, self._screenCoordinates], |
| 2444 |
) |
| 2445 |
), |
| 2446 |
) |
| 2447 |
) |
| 2448 |
dist = newpos - oldpos |
| 2449 |
self._screenCoordinates = coordinates |
| 2450 |
|
| 2451 |
if self.last_draw is not None: |
| 2452 |
graphics, xAxis, yAxis = self.last_draw |
| 2453 |
yAxis -= dist[1] |
| 2454 |
xAxis -= dist[0] |
| 2455 |
self._Draw(graphics, xAxis, yAxis) |
| 2456 |
|
| 2457 |
def OnMouseLeftDown(self, event): |
| 2458 |
"""Handle left mouse button down events. |
| 2459 |
|
| 2460 |
Args: |
| 2461 |
event (wx.Event): The event that triggered this method. |
| 2462 |
""" |
| 2463 |
self._zoomCorner1[0], self._zoomCorner1[1] = self._getXY(event) |
| 2464 |
self._screenCoordinates = np.array(event.GetPosition()) |
| 2465 |
if self._dragEnabled: |
| 2466 |
self.SetCursor(self.GrabHandCursor) |
| 2467 |
self.canvas.CaptureMouse() |
| 2468 |
|
| 2469 |
def OnMouseLeftUp(self, event): |
| 2470 |
"""Handle left mouse button up events. |
| 2471 |
|
| 2472 |
Args: |
| 2473 |
event (wx.Event): The event that triggered this method. |
| 2474 |
""" |
| 2475 |
if self._zoomEnabled and self._hasDragged: |
| 2476 |
self._drawRubberBand(self._zoomCorner1, self._zoomCorner2) # remove old |
| 2477 |
self._zoomCorner2[0], self._zoomCorner2[1] = self._getXY(event) |
| 2478 |
self._hasDragged = False # reset flag |
| 2479 |
minX, minY = np.minimum(self._zoomCorner1, self._zoomCorner2) |
| 2480 |
maxX, maxY = np.maximum(self._zoomCorner1, self._zoomCorner2) |
| 2481 |
self.last_PointLabel = None # reset pointLabel |
| 2482 |
if self.last_draw is not None: |
| 2483 |
self._Draw( |
| 2484 |
self.last_draw[0], |
| 2485 |
xAxis=(minX, maxX), |
| 2486 |
yAxis=(minY, maxY), |
| 2487 |
dc=None, |
| 2488 |
) |
| 2489 |
if self._dragEnabled: |
| 2490 |
self.SetCursor(self.HandCursor) |
| 2491 |
if self.canvas.HasCapture(): |
| 2492 |
self.canvas.ReleaseMouse() |
| 2493 |
|
| 2494 |
def OnMouseDoubleClick(self, event): |
| 2495 |
"""Handle double-click events. |
| 2496 |
|
| 2497 |
Args: |
| 2498 |
event (wx.Event): The event that triggered this method. |
| 2499 |
""" |
| 2500 |
if self._zoomEnabled: |
| 2501 |
# Give a little time for the click to be totally finished |
| 2502 |
# before (possibly) removing the scrollbars and trigering |
| 2503 |
# size events, etc. |
| 2504 |
wx.FutureCall(200, self.Reset) |
| 2505 |
|
| 2506 |
def OnMouseRightDown(self, event): |
| 2507 |
"""Handle right mouse button down events. |
| 2508 |
|
| 2509 |
Args: |
| 2510 |
event (wx.Event): The event that triggered this method. |
| 2511 |
""" |
| 2512 |
if self._zoomEnabled: |
| 2513 |
X, Y = self._getXY(event) |
| 2514 |
self.Zoom((X, Y), (self._zoomOutFactor, self._zoomOutFactor)) |
| 2515 |
|
| 2516 |
def OnPaint(self, event): |
| 2517 |
"""Handle paint events. |
| 2518 |
|
| 2519 |
Args: |
| 2520 |
event (wx.Event): The event that triggered this method. |
| 2521 |
""" |
| 2522 |
# All that is needed here is to draw the buffer to screen |
| 2523 |
if self.last_PointLabel is not None: |
| 2524 |
self._drawPointLabel(self.last_PointLabel) # erase old |
| 2525 |
self.last_PointLabel = None |
| 2526 |
dc = wx.BufferedPaintDC(self.canvas, self._Buffer) |
| 2527 |
if self._antiAliasingEnabled: |
| 2528 |
with contextlib.suppress(Exception): |
| 2529 |
dc = wx.GCDC(dc) |
| 2530 |
|
| 2531 |
def OnSize(self, event): |
| 2532 |
"""Handle size events. |
| 2533 |
|
| 2534 |
Args: |
| 2535 |
event (wx.Event): The event that triggered this method. |
| 2536 |
""" |
| 2537 |
# The Buffer init is done here, to make sure the buffer is always |
| 2538 |
# the same size as the Window |
| 2539 |
Size = self.canvas.GetClientSize() |
| 2540 |
Size.width = max(1, Size.width) |
| 2541 |
Size.height = max(1, Size.height) |
| 2542 |
|
| 2543 |
# Make new offscreen bitmap: this bitmap will always have the |
| 2544 |
# current drawing in it, so it can be used to save the image to |
| 2545 |
# a file, or whatever. |
| 2546 |
self._Buffer = wx.EmptyBitmap(Size.width, Size.height) |
| 2547 |
self._setSize() |
| 2548 |
|
| 2549 |
self.last_PointLabel = None # reset pointLabel |
| 2550 |
|
| 2551 |
if self.last_draw is None: |
| 2552 |
self.Clear() |
| 2553 |
else: |
| 2554 |
graphics, xSpec, ySpec = self.last_draw |
| 2555 |
self._Draw(graphics, xSpec, ySpec) |
| 2556 |
|
| 2557 |
def OnLeave(self, event): |
| 2558 |
"""Erase pointLabel when mouse outside window. |
| 2559 |
|
| 2560 |
Args: |
| 2561 |
event (wx.Event): The event that triggered this method. |
| 2562 |
""" |
| 2563 |
if self.last_PointLabel is not None: |
| 2564 |
self._drawPointLabel(self.last_PointLabel) # erase old |
| 2565 |
self.last_PointLabel = None |
| 2566 |
|
| 2567 |
def OnScroll(self, event): |
| 2568 |
"""Handle scrollbar events. |
| 2569 |
|
| 2570 |
Args: |
| 2571 |
event (wx.Event): The event that triggered this method. |
| 2572 |
""" |
| 2573 |
if self._adjustingSB: |
| 2574 |
return |
| 2575 |
|
| 2576 |
self._sb_ignore = True |
| 2577 |
sbpos = event.GetPosition() |
| 2578 |
|
| 2579 |
if event.GetOrientation() == wx.VERTICAL: |
| 2580 |
fullrange, pagesize = ( |
| 2581 |
self.sb_vert.GetRange(), |
| 2582 |
self.sb_vert.GetPageSize(), |
| 2583 |
) |
| 2584 |
sbpos = fullrange - pagesize - sbpos |
| 2585 |
dist = sbpos * self._sb_yunit - ( |
| 2586 |
self._getYCurrentRange()[0] - self._sb_yfullrange |
| 2587 |
) |
| 2588 |
self.ScrollUp(dist) |
| 2589 |
|
| 2590 |
if event.GetOrientation() == wx.HORIZONTAL: |
| 2591 |
dist = sbpos * self._sb_xunit - ( |
| 2592 |
self._getXCurrentRange()[0] - self._sb_xfullrange |
| 2593 |
) |
| 2594 |
self.ScrollRight(dist) |
| 2595 |
|
| 2596 |
# Private Methods ************************************************** |
| 2597 |
def _setSize(self, width=None, height=None): |
| 2598 |
"""DC width and height.""" |
| 2599 |
if width is None: |
| 2600 |
(self.width, self.height) = self.canvas.GetClientSize() |
| 2601 |
else: |
| 2602 |
self.width, self.height = width, height |
| 2603 |
self.width *= self._pointSize[0] # high precision |
| 2604 |
self.height *= self._pointSize[1] # high precision |
| 2605 |
self.plotbox_size = 0.97 * np.array([self.width, self.height]) |
| 2606 |
xo = 0.5 * (self.width - self.plotbox_size[0]) |
| 2607 |
yo = self.height - 0.5 * (self.height - self.plotbox_size[1]) |
| 2608 |
self.plotbox_origin = np.array([xo, yo]) |
| 2609 |
|
| 2610 |
def _setPrinterScale(self, scale): |
| 2611 |
"""Used to thicken lines and increase marker size for print out.""" |
| 2612 |
# line thickness on printer is very thin at 600 dot/in. Markers small |
| 2613 |
self.printerScale = scale |
| 2614 |
|
| 2615 |
def _printDraw(self, printDC): |
| 2616 |
"""Used for printing.""" |
| 2617 |
if self.last_draw is not None: |
| 2618 |
graphics, xSpec, ySpec = self.last_draw |
| 2619 |
self._Draw(graphics, xSpec, ySpec, printDC) |
| 2620 |
|
| 2621 |
def _drawPointLabel(self, mDataDict): |
| 2622 |
"""Draw and erases pointLabels.""" |
| 2623 |
width = self._Buffer.GetWidth() |
| 2624 |
height = self._Buffer.GetHeight() |
| 2625 |
tmp_Buffer = self._Buffer.GetSubBitmap((0, 0, width, height)) |
| 2626 |
dcs = wx.MemoryDC(self._Buffer) |
| 2627 |
self._pointLabelFunc(dcs, mDataDict) # custom user pointLabel function |
| 2628 |
|
| 2629 |
dc = wx.ClientDC(self.canvas) |
| 2630 |
dc = wx.BufferedDC(dc, self._Buffer) |
| 2631 |
# this will erase if called twice |
| 2632 |
dc.Blit(0, 0, width, height, dcs, 0, 0, self._logicalFunction) |
| 2633 |
self._Buffer = tmp_Buffer |
| 2634 |
if "gtk3" in wx.PlatformInfo: |
| 2635 |
self.Refresh() |
| 2636 |
self.Update() |
| 2637 |
|
| 2638 |
def _drawLegend( |
| 2639 |
self, dc, graphics, rhsW, topH, legendBoxWH, legendSymExt, legendTextExt |
| 2640 |
): |
| 2641 |
"""Draw legend symbols and text.""" |
| 2642 |
# top right hand corner of graph box is ref corner |
| 2643 |
trhc = self.plotbox_origin + ( |
| 2644 |
self.plotbox_size - [rhsW + self._pointSize[0], topH + self._pointSize[1]] |
| 2645 |
) * [1, -1] |
| 2646 |
# Draw a 20% transparent box behind legend so that if legend is inside |
| 2647 |
# graph it looks nicer on overlap |
| 2648 |
dc.SetPen(wx.TRANSPARENT_PEN) |
| 2649 |
c = wx.Colour() |
| 2650 |
c.Set( |
| 2651 |
self.BackgroundColour.red, |
| 2652 |
self.BackgroundColour.green, |
| 2653 |
self.BackgroundColour.blue, |
| 2654 |
204, |
| 2655 |
) |
| 2656 |
dc.SetBrush(wx.Brush(c)) |
| 2657 |
spacing = 0.0455 * legendBoxWH[0] |
| 2658 |
dc.DrawRectangle( |
| 2659 |
int(trhc[0] - spacing), |
| 2660 |
int(trhc[1]), |
| 2661 |
int(legendBoxWH[0] + spacing), |
| 2662 |
int(legendBoxWH[1] + self._pointSize[1] * 2), |
| 2663 |
) |
| 2664 |
legend_inside = True |
| 2665 |
# border space between legend sym and graph box |
| 2666 |
legendLHS = 0 if legend_inside else 0.091 * legendBoxWH[0] |
| 2667 |
lineHeight = ( |
| 2668 |
max(legendSymExt[1], legendTextExt[1]) * 1.1 |
| 2669 |
) # 1.1 used as space between lines |
| 2670 |
dc.SetFont(self._getFont(self._fontSizeLegend)) |
| 2671 |
n = 0 |
| 2672 |
for o in graphics: |
| 2673 |
legend = o.getLegend() |
| 2674 |
if not legend: |
| 2675 |
continue |
| 2676 |
s = n * lineHeight |
| 2677 |
n += 1 |
| 2678 |
if isinstance(o, PolyMarker): |
| 2679 |
# draw marker with legend |
| 2680 |
pnt = ( |
| 2681 |
trhc[0] + legendLHS + legendSymExt[0] / 2.0, |
| 2682 |
trhc[1] + s + lineHeight / 2.0, |
| 2683 |
) |
| 2684 |
o.draw(dc, self.printerScale, coord=np.array([pnt])) |
| 2685 |
elif isinstance(o, PolyLine): |
| 2686 |
# draw line with legend |
| 2687 |
pnt1 = (trhc[0] + legendLHS, trhc[1] + s + lineHeight / 2.0) |
| 2688 |
pnt2 = ( |
| 2689 |
trhc[0] + legendLHS + legendSymExt[0], |
| 2690 |
trhc[1] + s + lineHeight / 2.0, |
| 2691 |
) |
| 2692 |
o.draw(dc, self.printerScale, coord=np.array([pnt1, pnt2])) |
| 2693 |
else: |
| 2694 |
raise TypeError("object is neither PolyMarker or PolyLine instance") |
| 2695 |
# draw legend txt |
| 2696 |
pnt = ( |
| 2697 |
trhc[0] + legendLHS + legendSymExt[0] + 5 * self._pointSize[0], |
| 2698 |
trhc[1] + s + lineHeight / 2.0 - legendTextExt[1] / 2, |
| 2699 |
) |
| 2700 |
dc.DrawText(legend, int(pnt[0]), int(pnt[1])) |
| 2701 |
dc.SetFont(self._getFont(self._fontSizeAxis)) # reset |
| 2702 |
|
| 2703 |
def _titleLablesWH(self, dc, graphics): |
| 2704 |
"""Draw Title and labels and returns width and height for each.""" |
| 2705 |
# TextExtents for Title and Axis Labels |
| 2706 |
dc.SetFont(self._getFont(self._fontSizeTitle)) |
| 2707 |
if self._titleEnabled: |
| 2708 |
title = graphics.getTitle() |
| 2709 |
titleWH = dc.GetTextExtent(title) |
| 2710 |
else: |
| 2711 |
titleWH = (0, 0) |
| 2712 |
dc.SetFont(self._getFont(self._fontSizeAxis)) |
| 2713 |
xLabel, yLabel = graphics.getXLabel(), graphics.getYLabel() |
| 2714 |
xLabelWH = dc.GetTextExtent(xLabel) |
| 2715 |
yLabelWH = dc.GetTextExtent(yLabel) |
| 2716 |
return titleWH, xLabelWH, yLabelWH |
| 2717 |
|
| 2718 |
def _legendWH(self, dc, graphics): |
| 2719 |
"""Return the size in screen units for legend box.""" |
| 2720 |
txtExt = (0, 0) |
| 2721 |
if not self._legendEnabled: |
| 2722 |
legendBoxWH = symExt = txtExt |
| 2723 |
else: |
| 2724 |
# find max symbol size |
| 2725 |
symExt = graphics.getSymExtent(self.printerScale) |
| 2726 |
# find max legend text extent |
| 2727 |
dc.SetFont(self._getFont(self._fontSizeLegend)) |
| 2728 |
txtList = graphics.getLegendNames() |
| 2729 |
for txt in txtList: |
| 2730 |
txtExt = np.maximum(txtExt, dc.GetTextExtent(txt)) |
| 2731 |
maxW = symExt[0] + txtExt[0] |
| 2732 |
maxH = max(symExt[1], txtExt[1]) |
| 2733 |
# padding .1 for lhs of legend box and space between lines |
| 2734 |
maxW = maxW * 1.1 |
| 2735 |
maxH = maxH * 1.1 * len(txtList) |
| 2736 |
dc.SetFont(self._getFont(self._fontSizeAxis)) |
| 2737 |
legendBoxWH = (maxW, maxH) |
| 2738 |
return (legendBoxWH, symExt, txtExt) |
| 2739 |
|
| 2740 |
def _drawRubberBand(self, corner1, corner2): |
| 2741 |
"""Draws/erases rect box from corner1 to corner2.""" |
| 2742 |
ptx, pty, rectWidth, rectHeight = self._point2ClientCoord(corner1, corner2) |
| 2743 |
# draw rectangle |
| 2744 |
dc = wx.ClientDC(self.canvas) |
| 2745 |
dc.SetPen(wx.Pen(wx.BLACK)) |
| 2746 |
dc.SetBrush(wx.Brush(wx.WHITE, wx.BRUSHSTYLE_TRANSPARENT)) |
| 2747 |
dc.SetLogicalFunction(wx.INVERT) |
| 2748 |
dc.DrawRectangle(ptx, pty, rectWidth, rectHeight) |
| 2749 |
dc.SetLogicalFunction(wx.COPY) |
| 2750 |
if "gtk3" in wx.PlatformInfo: |
| 2751 |
self.Refresh() |
| 2752 |
self.Update() |
| 2753 |
|
| 2754 |
def _getFont(self, size): |
| 2755 |
"""Take font size, adjusts if printing and returns wx.Font.""" |
| 2756 |
s = size * self.printerScale * self._fontScale |
| 2757 |
of = self.GetFont() |
| 2758 |
# Linux speed up to get font from cache rather than X font server |
| 2759 |
key = (int(s), of.GetFamily(), of.GetStyle(), of.GetWeight(), of.GetFaceName()) |
| 2760 |
font = self._fontCache.get(key, None) |
| 2761 |
if font: |
| 2762 |
return font # yeah! cache hit |
| 2763 |
kwarg = "faceName" if "phoenix" in wx.PlatformInfo else "face" |
| 2764 |
font = wx.Font( |
| 2765 |
int(s), |
| 2766 |
of.GetFamily(), |
| 2767 |
of.GetStyle(), |
| 2768 |
of.GetWeight(), |
| 2769 |
**{kwarg: of.GetFaceName()}, |
| 2770 |
) |
| 2771 |
self._fontCache[key] = font |
| 2772 |
return font |
| 2773 |
|
| 2774 |
def _point2ClientCoord(self, corner1, corner2): |
| 2775 |
"""Convert user point coords to client screen int coords x, y, width, height.""" |
| 2776 |
c1 = np.array(corner1) |
| 2777 |
c2 = np.array(corner2) |
| 2778 |
# convert to screen coords |
| 2779 |
pt1 = c1 * self._pointScale + self._pointShift |
| 2780 |
pt2 = c2 * self._pointScale + self._pointShift |
| 2781 |
# make height and width positive |
| 2782 |
pul = np.minimum(pt1, pt2) # Upper left corner |
| 2783 |
plr = np.maximum(pt1, pt2) # Lower right corner |
| 2784 |
rectWidth, rectHeight = plr - pul |
| 2785 |
ptx, pty = pul |
| 2786 |
return ptx, pty, rectWidth, rectHeight |
| 2787 |
|
| 2788 |
def _axisInterval(self, spec, lower, upper): |
| 2789 |
"""Return sensible axis range for given spec.""" |
| 2790 |
if spec in {"none", "min"} or isinstance(spec, (float, int)): |
| 2791 |
if lower == upper: |
| 2792 |
return lower - 0.5, upper + 0.5 |
| 2793 |
return lower, upper |
| 2794 |
if spec == "auto": |
| 2795 |
axis_range = upper - lower |
| 2796 |
if axis_range == 0.0: |
| 2797 |
return lower - 0.5, upper + 0.5 |
| 2798 |
log = np.log10(axis_range) |
| 2799 |
power = np.floor(log) |
| 2800 |
fraction = log - power |
| 2801 |
if fraction <= 0.05: |
| 2802 |
power = power - 1 |
| 2803 |
grid = 10.0**power |
| 2804 |
lower = lower - lower % grid |
| 2805 |
mod = upper % grid |
| 2806 |
if mod != 0: |
| 2807 |
upper = upper - mod + grid |
| 2808 |
return lower, upper |
| 2809 |
if isinstance(spec, tuple): |
| 2810 |
lower, upper = spec |
| 2811 |
if lower <= upper: |
| 2812 |
return lower, upper |
| 2813 |
return upper, lower |
| 2814 |
raise ValueError(str(spec) + ": illegal axis specification") |
| 2815 |
|
| 2816 |
def _drawAxes(self, dc, p1, p2, scale, shift, xticks, yticks): |
| 2817 |
penWidth = ( |
| 2818 |
self.printerScale * self._pointSize[0] |
| 2819 |
) # increases thickness for printing only |
| 2820 |
dc.SetPen(wx.Pen(self._gridColour, int(penWidth))) |
| 2821 |
|
| 2822 |
# set length of tick marks--long ones make grid |
| 2823 |
if self._gridEnabled: |
| 2824 |
x, y, width, height = self._point2ClientCoord(p1, p2) |
| 2825 |
if self._gridEnabled == "Horizontal": |
| 2826 |
yTickLength = (width / 2.0 + 1) * self._pointSize[1] |
| 2827 |
xTickLength = 3 * self.printerScale * self._pointSize[0] |
| 2828 |
elif self._gridEnabled == "Vertical": |
| 2829 |
yTickLength = 3 * self.printerScale * self._pointSize[1] |
| 2830 |
xTickLength = (height / 2.0 + 1) * self._pointSize[0] |
| 2831 |
else: |
| 2832 |
yTickLength = (width / 2.0 + 1) * self._pointSize[1] |
| 2833 |
xTickLength = (height / 2.0 + 1) * self._pointSize[0] |
| 2834 |
else: |
| 2835 |
yTickLength = ( |
| 2836 |
3 * self.printerScale * self._pointSize[1] |
| 2837 |
) # lengthens lines for printing |
| 2838 |
xTickLength = 3 * self.printerScale * self._pointSize[0] |
| 2839 |
|
| 2840 |
if self._ticksEnabled: |
| 2841 |
# get the tick lengths so that labels don't overlap |
| 2842 |
xoffset = self.tickLengthScale[0] |
| 2843 |
yoffset = self.tickLengthScale[1] |
| 2844 |
# only care about negative (out of plot area) tick lengths. |
| 2845 |
xoffset = xoffset if xoffset < 0 else 0 |
| 2846 |
yoffset = yoffset if yoffset < 0 else 0 |
| 2847 |
else: |
| 2848 |
xoffset = yoffset = 0 |
| 2849 |
|
| 2850 |
if self._xSpec != "none": |
| 2851 |
lower, upper = p1[0], p2[0] |
| 2852 |
text = 1 |
| 2853 |
for y, d in [ |
| 2854 |
(p1[1], -xTickLength), |
| 2855 |
(p2[1], xTickLength), |
| 2856 |
]: # miny, maxy and tick lengths |
| 2857 |
for x, label in xticks: |
| 2858 |
w = dc.GetTextExtent(label)[0] |
| 2859 |
pt = scale * np.array([x, y]) + shift |
| 2860 |
dc.DrawLine( |
| 2861 |
int(pt[0]), int(pt[1]), int(pt[0]), int(pt[1] + d) |
| 2862 |
) # draws tick mark d units |
| 2863 |
if text: |
| 2864 |
dc.DrawText( |
| 2865 |
label, |
| 2866 |
int(pt[0] - w / 2.0), |
| 2867 |
int(pt[1] + 2 * self._pointSize[1] - xoffset), |
| 2868 |
) |
| 2869 |
a1 = scale * np.array([lower, y]) + shift |
| 2870 |
a2 = scale * np.array([upper, y]) + shift |
| 2871 |
dc.DrawLine( |
| 2872 |
int(a1[0]), int(a1[1]), int(a2[0]), int(a2[1]) |
| 2873 |
) # draws upper and lower axis line |
| 2874 |
text = 0 # axis values not drawn on top side |
| 2875 |
|
| 2876 |
if self._ySpec != "none": |
| 2877 |
lower, upper = p1[1], p2[1] |
| 2878 |
text = 1 |
| 2879 |
h = dc.GetCharHeight() |
| 2880 |
for x, d in [(p1[0], -yTickLength), (p2[0], yTickLength)]: |
| 2881 |
for y, label in yticks: |
| 2882 |
w = dc.GetTextExtent(label)[0] |
| 2883 |
pt = scale * np.array([x, y]) + shift |
| 2884 |
dc.DrawLine(int(pt[0]), int(pt[1]), int(pt[0] - d), int(pt[1])) |
| 2885 |
if text: |
| 2886 |
dc.DrawText( |
| 2887 |
label, |
| 2888 |
int(pt[0] - w - 3 * self._pointSize[0] + yoffset), |
| 2889 |
int(pt[1] - 0.5 * h), |
| 2890 |
) |
| 2891 |
a1 = scale * np.array([x, lower]) + shift |
| 2892 |
a2 = scale * np.array([x, upper]) + shift |
| 2893 |
dc.DrawLine(int(a1[0]), int(a1[1]), int(a2[0]), int(a2[1])) |
| 2894 |
text = 0 # axis values not drawn on right side |
| 2895 |
|
| 2896 |
@TempStyle("pen") |
| 2897 |
def _drawTicks(self, dc, p1, p2, scale, shift, xticks, yticks): |
| 2898 |
"""Draw the tick marks. |
| 2899 |
|
| 2900 |
Args: |
| 2901 |
dc (wx.DC): The :class:`wx.DC` to draw on. |
| 2902 |
p1 (np.array): The lower-left hand corner of the plot in plot |
| 2903 |
coords. So, if the plot ranges from x=-10 to 10 and y=-5 to 5, |
| 2904 |
then p1 = (-10, -5). |
| 2905 |
p2 (np.array): The upper-right hand corner of the plot in plot |
| 2906 |
coords. So, if the plot ranges from x=-10 to 10 and y=-5 to 5, |
| 2907 |
then p2 = (10, 5). |
| 2908 |
scale (np.array): The [X, Y] scaling factor to convert plot coords |
| 2909 |
to DC coords. |
| 2910 |
shift (np.array): The [X, Y] shift values to convert plot coords to |
| 2911 |
DC coords. Must be in plot units, not DC units. |
| 2912 |
xticks (list): The X tick definition. |
| 2913 |
yticks (list): The Y tick definition. |
| 2914 |
""" |
| 2915 |
# TODO: add option for ticks to extend outside of graph |
| 2916 |
# - done via negative ticklength values? |
| 2917 |
# + works but the axes values cut off the ticks. |
| 2918 |
# increases thickness for printing only |
| 2919 |
pen = self.tickPen |
| 2920 |
penWidth = self.printerScale * pen.GetWidth() |
| 2921 |
pen.SetWidth(penWidth) |
| 2922 |
dc.SetPen(pen) |
| 2923 |
|
| 2924 |
# lengthen lines for printing |
| 2925 |
xTickLength = self.tickLengthScale[0] |
| 2926 |
yTickLength = self.tickLengthScale[1] |
| 2927 |
|
| 2928 |
ticks = self.enableTicks |
| 2929 |
if self.xSpec != "none": # I don't like this :-/ |
| 2930 |
if ticks.bottom: |
| 2931 |
lines = [] |
| 2932 |
for x, _label in xticks: |
| 2933 |
pt = scale_and_shift_point(x, p1[1], scale, shift) |
| 2934 |
lines.append( |
| 2935 |
(int(pt[0]), int(pt[1]), int(pt[0]), int(pt[1] - xTickLength)) |
| 2936 |
) |
| 2937 |
dc.DrawLineList(lines) |
| 2938 |
if ticks.top: |
| 2939 |
lines = [] |
| 2940 |
for x, _label in xticks: |
| 2941 |
pt = scale_and_shift_point(x, p2[1], scale, shift) |
| 2942 |
lines.append( |
| 2943 |
(int(pt[0]), int(pt[1]), int(pt[0]), int(pt[1] + xTickLength)) |
| 2944 |
) |
| 2945 |
dc.DrawLineList(lines) |
| 2946 |
|
| 2947 |
if self.ySpec != "none": |
| 2948 |
if ticks.left: |
| 2949 |
lines = [] |
| 2950 |
for y, _label in yticks: |
| 2951 |
pt = scale_and_shift_point(p1[0], y, scale, shift) |
| 2952 |
lines.append( |
| 2953 |
(int(pt[0]), int(pt[1]), int(pt[0] + yTickLength), int(pt[1])) |
| 2954 |
) |
| 2955 |
dc.DrawLineList(lines) |
| 2956 |
if ticks.right: |
| 2957 |
lines = [] |
| 2958 |
for y, _label in yticks: |
| 2959 |
pt = scale_and_shift_point(p2[0], y, scale, shift) |
| 2960 |
lines.append( |
| 2961 |
(int(pt[0]), int(pt[1]), int(pt[0] - yTickLength), int(pt[1])) |
| 2962 |
) |
| 2963 |
dc.DrawLineList(lines) |
| 2964 |
|
| 2965 |
def _drawExtras(self, dc, p1, p2, scale, shift): |
| 2966 |
b1, b2 = self.last_draw[0].boundingBox() |
| 2967 |
|
| 2968 |
if self._centerLinesEnabled: |
| 2969 |
x, y = [b1[i] + (b2[i] - b1[i]) / 2.0 for i in range(2)] |
| 2970 |
x, y = self.PositionUserToScreen((x, y)) |
| 2971 |
x, y = x * self._pointSize[0], y * self._pointSize[1] |
| 2972 |
if self._centerLinesEnabled in ("Horizontal", True): |
| 2973 |
dc.DrawLine( |
| 2974 |
int(scale[0] * p1[0] + shift[0]), |
| 2975 |
int(y), |
| 2976 |
int(scale[0] * p2[0] + shift[0]), |
| 2977 |
int(y), |
| 2978 |
) |
| 2979 |
if self._centerLinesEnabled in ("Vertical", True): |
| 2980 |
dc.DrawLine( |
| 2981 |
int(x), |
| 2982 |
int(scale[1] * p1[1] + shift[1]), |
| 2983 |
int(x), |
| 2984 |
int(scale[1] * p2[1] + shift[1]), |
| 2985 |
) |
| 2986 |
|
| 2987 |
if self._diagonalsEnabled: |
| 2988 |
x1, y1 = self.PositionUserToScreen(b1) |
| 2989 |
x1, y1 = x1 * self._pointSize[0], y1 * self._pointSize[1] |
| 2990 |
x2, y2 = self.PositionUserToScreen(b2) |
| 2991 |
x2, y2 = x2 * self._pointSize[0], y2 * self._pointSize[1] |
| 2992 |
if self._diagonalsEnabled in ("Bottomleft-Topright", True): |
| 2993 |
dc.DrawLine(int(x1), int(y1), int(x2), int(y2)) |
| 2994 |
if self._diagonalsEnabled in ("Bottomright-Topleft", True): |
| 2995 |
dc.DrawLine(int(x1), int(y2), int(x2), int(y1)) |
| 2996 |
|
| 2997 |
def _drawAxesLabels( |
| 2998 |
self, dc, graphics, lhsW, rhsW, bottomH, topH, xLabelWH, yLabelWH |
| 2999 |
): |
| 3000 |
"""Draw the axes labels.""" |
| 3001 |
if self._ticksEnabled: |
| 3002 |
# get the tick lengths so that labels don't overlap |
| 3003 |
xTickLength = self.tickLengthScale[0] |
| 3004 |
yTickLength = self.tickLengthScale[1] |
| 3005 |
# only care about negative (out of plot area) tick lengths. |
| 3006 |
xTickLength = xTickLength if xTickLength < 0 else 0 |
| 3007 |
yTickLength = yTickLength if yTickLength < 0 else 0 |
| 3008 |
else: |
| 3009 |
xTickLength = yTickLength = 0 |
| 3010 |
|
| 3011 |
# TODO: axes values get big when this is turned off |
| 3012 |
dc.SetFont(self._getFont(self._fontSizeAxis)) |
| 3013 |
xLabelPos = ( |
| 3014 |
self.plotbox_origin[0] |
| 3015 |
+ lhsW |
| 3016 |
+ (self.plotbox_size[0] - lhsW - rhsW) / 2.0 |
| 3017 |
- xLabelWH[0] / 2.0, |
| 3018 |
self.plotbox_origin[1] - xLabelWH[1] - yTickLength, |
| 3019 |
) |
| 3020 |
dc.DrawText(graphics.xLabel, int(xLabelPos[0]), int(xLabelPos[1])) |
| 3021 |
yLabelPos = ( |
| 3022 |
self.plotbox_origin[0] - 1 * self._pointSize[0] + xTickLength, |
| 3023 |
self.plotbox_origin[1] |
| 3024 |
- bottomH |
| 3025 |
- (self.plotbox_size[1] - bottomH - topH) / 2.0 |
| 3026 |
+ yLabelWH[0] / 2.0, |
| 3027 |
) |
| 3028 |
if graphics.yLabel: # bug fix for Linux |
| 3029 |
dc.DrawRotatedText( |
| 3030 |
graphics.yLabel, int(yLabelPos[0]), int(yLabelPos[1]), 90 |
| 3031 |
) |
| 3032 |
|
| 3033 |
def _xticks(self, *args): |
| 3034 |
if self._logscale[0]: |
| 3035 |
return self._logticks(*args) |
| 3036 |
attr = {"numticks": self._xSpec} |
| 3037 |
return self._ticks(*args, **attr) |
| 3038 |
|
| 3039 |
def _yticks(self, *args): |
| 3040 |
if self._logscale[1]: |
| 3041 |
return self._logticks(*args) |
| 3042 |
attr = {"numticks": self._ySpec} |
| 3043 |
return self._ticks(*args, **attr) |
| 3044 |
|
| 3045 |
def _logticks(self, lower, upper): |
| 3046 |
# lower,upper = map(np.log10,[lower,upper]) |
| 3047 |
# print 'logticks',lower,upper |
| 3048 |
ticks = [] |
| 3049 |
mag = np.power(10, np.floor(lower)) |
| 3050 |
if upper - lower > 6: |
| 3051 |
t = np.power(10, np.ceil(lower)) |
| 3052 |
base = np.power(10, np.floor((upper - lower) / 6)) |
| 3053 |
|
| 3054 |
def inc(t): |
| 3055 |
return t * base - t |
| 3056 |
|
| 3057 |
else: |
| 3058 |
t = np.ceil(np.power(10, lower) / mag) * mag |
| 3059 |
|
| 3060 |
def inc(t): |
| 3061 |
return 10 ** int(np.floor(np.log10(t) + 1e-16)) |
| 3062 |
|
| 3063 |
majortick = int(np.log10(mag)) |
| 3064 |
while t <= pow(10, upper): |
| 3065 |
if majortick != int(np.floor(np.log10(t) + 1e-16)): |
| 3066 |
majortick = int(np.floor(np.log10(t) + 1e-16)) |
| 3067 |
ticklabel = f"1e{majortick}" |
| 3068 |
elif upper - lower < 2: |
| 3069 |
minortick = int(t / pow(10, majortick) + 0.5) |
| 3070 |
ticklabel = f"{minortick}e{majortick}" |
| 3071 |
else: |
| 3072 |
ticklabel = "" |
| 3073 |
ticks.append((np.log10(t), ticklabel)) |
| 3074 |
t += inc(t) |
| 3075 |
if len(ticks) == 0: |
| 3076 |
ticks = [(0, "")] |
| 3077 |
return ticks |
| 3078 |
|
| 3079 |
def _ticks(self, lower, upper, numticks=None): |
| 3080 |
if isinstance(numticks, (float, int)): |
| 3081 |
ideal = (upper - lower) / float(numticks) |
| 3082 |
else: |
| 3083 |
ideal = (upper - lower) / 7.0 |
| 3084 |
log = np.log10(ideal) |
| 3085 |
power = np.floor(log) |
| 3086 |
if isinstance(numticks, (float, int)): |
| 3087 |
grid = ideal |
| 3088 |
else: |
| 3089 |
fraction = log - power |
| 3090 |
factor = 1.0 |
| 3091 |
error = fraction |
| 3092 |
for f, lf in self._multiples: |
| 3093 |
e = np.fabs(fraction - lf) |
| 3094 |
if e < error: |
| 3095 |
error = e |
| 3096 |
factor = f |
| 3097 |
grid = factor * 10.0**power |
| 3098 |
if self._useScientificNotation and (power > 4 or power < -4): |
| 3099 |
file_format = "%+7.1e" |
| 3100 |
else: |
| 3101 |
if ideal > int(ideal): |
| 3102 |
fdigits = len(str(round(ideal, 4)).split(".")[-1][:4].rstrip("0")) |
| 3103 |
else: |
| 3104 |
fdigits = 0 |
| 3105 |
if power >= 0: |
| 3106 |
digits = max(1, int(power)) |
| 3107 |
file_format = f"%{digits!r}.{fdigits!r}f" |
| 3108 |
else: |
| 3109 |
digits = -int(power) |
| 3110 |
file_format = f"%{digits + 2!r}.{fdigits!r}f" |
| 3111 |
ticks = [] |
| 3112 |
t = -grid * np.floor(-lower / grid) |
| 3113 |
while t <= upper: |
| 3114 |
if t == -0: |
| 3115 |
t = 0 |
| 3116 |
ticks.append((t, file_format % (t,))) |
| 3117 |
t = t + grid |
| 3118 |
return ticks |
| 3119 |
|
| 3120 |
def _adjustScrollbars(self): |
| 3121 |
if self._sb_ignore: |
| 3122 |
self._sb_ignore = False |
| 3123 |
return |
| 3124 |
|
| 3125 |
if not self.GetShowScrollbars(): |
| 3126 |
return |
| 3127 |
|
| 3128 |
self._adjustingSB = True |
| 3129 |
needScrollbars = False |
| 3130 |
|
| 3131 |
# horizontal scrollbar |
| 3132 |
r_current = self._getXCurrentRange() |
| 3133 |
r_max = list(self._getXMaxRange()) |
| 3134 |
sbfullrange = float(self.sb_hor.GetRange()) |
| 3135 |
|
| 3136 |
r_max[0] = min(r_max[0], r_current[0]) |
| 3137 |
r_max[1] = max(r_max[1], r_current[1]) |
| 3138 |
|
| 3139 |
self._sb_xfullrange = r_max |
| 3140 |
|
| 3141 |
unit = (r_max[1] - r_max[0]) / float(self.sb_hor.GetRange()) |
| 3142 |
pos = int((r_current[0] - r_max[0]) / unit) |
| 3143 |
|
| 3144 |
if pos >= 0: |
| 3145 |
pagesize = int((r_current[1] - r_current[0]) / unit) |
| 3146 |
|
| 3147 |
self.sb_hor.SetScrollbar(pos, pagesize, sbfullrange, pagesize) |
| 3148 |
self._sb_xunit = unit |
| 3149 |
needScrollbars = needScrollbars or (pagesize != sbfullrange) |
| 3150 |
else: |
| 3151 |
self.sb_hor.SetScrollbar(0, 1000, 1000, 1000) |
| 3152 |
|
| 3153 |
# vertical scrollbar |
| 3154 |
r_current = self._getYCurrentRange() |
| 3155 |
r_max = list(self._getYMaxRange()) |
| 3156 |
sbfullrange = float(self.sb_vert.GetRange()) |
| 3157 |
|
| 3158 |
r_max[0] = min(r_max[0], r_current[0]) |
| 3159 |
r_max[1] = max(r_max[1], r_current[1]) |
| 3160 |
|
| 3161 |
self._sb_yfullrange = r_max |
| 3162 |
|
| 3163 |
unit = (r_max[1] - r_max[0]) / sbfullrange |
| 3164 |
pos = int((r_current[0] - r_max[0]) / unit) |
| 3165 |
|
| 3166 |
if pos >= 0: |
| 3167 |
pagesize = int((r_current[1] - r_current[0]) / unit) |
| 3168 |
pos = sbfullrange - 1 - pos - pagesize |
| 3169 |
self.sb_vert.SetScrollbar(pos, pagesize, sbfullrange, pagesize) |
| 3170 |
self._sb_yunit = unit |
| 3171 |
needScrollbars = needScrollbars or (pagesize != sbfullrange) |
| 3172 |
else: |
| 3173 |
self.sb_vert.SetScrollbar(0, 1000, 1000, 1000) |
| 3174 |
|
| 3175 |
self.SetShowScrollbars(needScrollbars) |
| 3176 |
self._adjustingSB = False |
| 3177 |
|
| 3178 |
|
| 3179 |
# ------------------------------------------------------------------------------- |
| 3180 |
# Used to layout the printer page |
| 3181 |
|
| 3182 |
|
| 3183 |
class PlotPrintout(wx.Printout): |
| 3184 |
"""Controls how the plot is made in printing and previewing. |
| 3185 |
|
| 3186 |
Args: |
| 3187 |
graph (PlotCanvas): The PlotCanvas instance to be printed or previewed. |
| 3188 |
""" |
| 3189 |
|
| 3190 |
# Do not change method names in this class, |
| 3191 |
# we have to override wx.Printout methods here! |
| 3192 |
def __init__(self, graph: PlotCanvas): |
| 3193 |
wx.Printout.__init__(self) |
| 3194 |
self.graph = graph |
| 3195 |
|
| 3196 |
def HasPage(self, page): |
| 3197 |
"""Check if the page exists. |
| 3198 |
|
| 3199 |
Args: |
| 3200 |
page (int): The page number to check. |
| 3201 |
|
| 3202 |
Returns: |
| 3203 |
bool: True if the page exists, False otherwise. |
| 3204 |
""" |
| 3205 |
return page == 1 |
| 3206 |
|
| 3207 |
def GetPageInfo(self): |
| 3208 |
"""Return the page information for printing or previewing. |
| 3209 |
|
| 3210 |
Returns: |
| 3211 |
tuple: A tuple containing the page information in the format |
| 3212 |
(minPage, maxPage, selPageFrom, selPageTo). |
| 3213 |
Here, we disable page numbers. |
| 3214 |
""" |
| 3215 |
return (1, 1, 1, 1) # disable page numbers |
| 3216 |
|
| 3217 |
def OnPrintPage(self, page): |
| 3218 |
"""Called by wx when printing or previewing. |
| 3219 |
|
| 3220 |
Args: |
| 3221 |
page (int): The page number being printed or previewed. |
| 3222 |
|
| 3223 |
Returns: |
| 3224 |
bool: True if the page was printed successfully, False otherwise. |
| 3225 |
""" |
| 3226 |
dc = self.GetDC() # allows using floats for certain functions |
| 3227 |
# Note PPIScreen does not give the correct number |
| 3228 |
# Calulate everything for printer and then scale for preview |
| 3229 |
PPIPrinter = self.GetPPIPrinter() # printer dots/inch (w,h) |
| 3230 |
# PPIScreen = self.GetPPIScreen() # screen dots/inch (w,h) |
| 3231 |
dcSize = dc.GetSize() # DC size |
| 3232 |
if self.graph._antiAliasingEnabled and not isinstance(dc, wx.GCDC): |
| 3233 |
try: |
| 3234 |
dc = wx.GCDC(dc) |
| 3235 |
except Exception: |
| 3236 |
pass |
| 3237 |
else: |
| 3238 |
if self.graph._hiResEnabled: |
| 3239 |
dc.SetMapMode( |
| 3240 |
wx.MM_TWIPS |
| 3241 |
) # high precision - each logical unit is 1/20 of a point |
| 3242 |
pageSize = self.GetPageSizePixels() # page size in terms of pixcels |
| 3243 |
clientDcSize = self.graph.GetClientSize() |
| 3244 |
|
| 3245 |
# find what the margins are (mm) |
| 3246 |
margLeftSize, margTopSize = self.graph.pageSetupData.GetMarginTopLeft() |
| 3247 |
margRightSize, margBottomSize = self.graph.pageSetupData.GetMarginBottomRight() |
| 3248 |
|
| 3249 |
# calculate offset and scale for dc |
| 3250 |
pixLeft = margLeftSize * PPIPrinter[0] / 25.4 # mm*(dots/in)/(mm/in) |
| 3251 |
pixRight = margRightSize * PPIPrinter[0] / 25.4 |
| 3252 |
pixTop = margTopSize * PPIPrinter[1] / 25.4 |
| 3253 |
pixBottom = margBottomSize * PPIPrinter[1] / 25.4 |
| 3254 |
|
| 3255 |
plotAreaW = pageSize[0] - (pixLeft + pixRight) |
| 3256 |
plotAreaH = pageSize[1] - (pixTop + pixBottom) |
| 3257 |
|
| 3258 |
# ratio offset and scale to screen size if preview |
| 3259 |
if self.IsPreview(): |
| 3260 |
ratioW = float(dcSize[0]) / pageSize[0] |
| 3261 |
ratioH = float(dcSize[1]) / pageSize[1] |
| 3262 |
pixLeft *= ratioW |
| 3263 |
pixTop *= ratioH |
| 3264 |
plotAreaW *= ratioW |
| 3265 |
plotAreaH *= ratioH |
| 3266 |
|
| 3267 |
# rescale plot to page or preview plot area |
| 3268 |
self.graph._setSize(plotAreaW, plotAreaH) |
| 3269 |
|
| 3270 |
# Set offset and scale |
| 3271 |
dc.SetDeviceOrigin(pixLeft, pixTop) |
| 3272 |
|
| 3273 |
# Thicken up pens and increase marker size for printing |
| 3274 |
ratioW = float(plotAreaW) / clientDcSize[0] |
| 3275 |
ratioH = float(plotAreaH) / clientDcSize[1] |
| 3276 |
aveScale = (ratioW + ratioH) / 2 |
| 3277 |
if self.graph._antiAliasingEnabled and not self.IsPreview(): |
| 3278 |
scale = dc.GetUserScale() |
| 3279 |
dc.SetUserScale( |
| 3280 |
scale[0] / self.graph._pointSize[0], scale[1] / self.graph._pointSize[1] |
| 3281 |
) |
| 3282 |
self.graph._setPrinterScale(aveScale) # tickens up pens for printing |
| 3283 |
|
| 3284 |
self.graph._printDraw(dc) |
| 3285 |
# rescale back to original |
| 3286 |
self.graph._setSize() |
| 3287 |
self.graph._setPrinterScale(1) |
| 3288 |
self.graph.Redraw() # to get point label scale and shift correct |
| 3289 |
|
| 3290 |
return True |
| 3291 |
|
| 3292 |
|
| 3293 |
# ---------------------------------------------------------------------- |
| 3294 |
try: |
| 3295 |
from DisplayCAL.embeddedimage import PyEmbeddedImage |
| 3296 |
except ImportError: |
| 3297 |
from wx.lib.embeddedimage import PyEmbeddedImage |
| 3298 |
|
| 3299 |
MagPlus = PyEmbeddedImage( |
| 3300 |
"iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAOFJ" |
| 3301 |
"REFUeJy1VdEOxCAIo27//8XbuKfuPASGZ0Zisoi2FJABbZM3bY8c13lo5GvbjioBPAUEB0Yc" |
| 3302 |
"VZ0iGRRc56Ee8DcikEgrJD8EFpzRegQASiRtBtzuA0hrdRPYQxaEKyJPG6IHyiK3xnNZvUSS" |
| 3303 |
"NvUuzgYh0il4y14nCFPk5XgmNbRbQbVotGo9msj47G3UXJ7fuz8Q8FAGEu0/PbZh2D3NoshU" |
| 3304 |
"1VUydBGVZKMimlGeErdNGUmf/x7YpjMjcf8HVYvS2adr6aFVlCy/5Ijk9q8SeCR9isJR8SeJ" |
| 3305 |
"8pv7S0Wu2Acr0qdj3w7DRAAAAABJRU5ErkJggg==" |
| 3306 |
) |
| 3307 |
|
| 3308 |
GrabHand = PyEmbeddedImage( |
| 3309 |
"iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAARFJ" |
| 3310 |
"REFUeJy1VdESgzAIS2j//4s3s5fRQ6Rad5M7H0oxCZhWSpK1TjwUBCBJAIBItL1fijlfe1yJ" |
| 3311 |
"8noCGC9KgrXO7f0SyZEDAF/H2opsAHv9V/548nplT5Jo7YAFQKQ1RMWzmHUS96suqdBrHkuV" |
| 3312 |
"uxpdJjCS8CfGXWdJ2glzcquKSR5c46QOtCpgNyIHj6oieAXg3282QvMX45hy8a8H0VonJZUO" |
| 3313 |
"clesjOPg/dhBTq64o1Kacz4Ri2x5RKsf8+wcWQaJJL+A+xRcZHeQeBKjK+5EFiVJ4xy4x2Mn" |
| 3314 |
"1Vk4U5/DWmfPieiqbye7a3tV/cCsWKu76K76KUFFchVnhigJ/hmktelm/m3e3b8k+Ec8PqLH" |
| 3315 |
"CT4JRfyK9o1xYwAAAABJRU5ErkJggg==" |
| 3316 |
) |
| 3317 |
|
| 3318 |
Hand = PyEmbeddedImage( |
| 3319 |
"iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAARBJ" |
| 3320 |
"REFUeJytluECwiAIhDn1/Z942/UnjCGoq+6XNeWDC1xAqbKr6zyo61Ibds60J8GBT0yS3IEM" |
| 3321 |
"ABuIpJTa4IOLiAAQksuKyixLH1ShHgTgZl8KiALxOsODPoEMkgJ25Su6zoO3ZrjRnI96OLIq" |
| 3322 |
"k7dsqOCboDa4XV/nwQEQVeFtmMnvbSJja+oagKBUaLn9hzd7VipRa9ostIv0O1uhzzaqNJxk" |
| 3323 |
"hViwDVxqg51kksMg9r2rDDIFwHCap130FBhdMzeAfWg//6Ki5WWQrHSv6EIUeVs0g3wT3J7r" |
| 3324 |
"FmWQp/JJDXeRh2TXcJa91zAH2uN2mvXFsrIrsjS8rnftWmWfAiLIStuD9m9h9belvzgS/1fP" |
| 3325 |
"X7075IwDENteAAAAAElFTkSuQmCC" |
| 3326 |
) |
| 3327 |
|
| 3328 |
# --------------------------------------------------------------------------- |
| 3329 |
# if running standalone... |
| 3330 |
# |
| 3331 |
# ...a sample implementation using the above |
| 3332 |
# |
| 3333 |
|
| 3334 |
|
| 3335 |
def _draw1Objects(): |
| 3336 |
"""Draw a plot with a single line. |
| 3337 |
|
| 3338 |
Returns: |
| 3339 |
PlotGraphics: A plot with a single line and markers. |
| 3340 |
""" |
| 3341 |
# 100 points sin function, plotted as green circles |
| 3342 |
data1 = 2.0 * np.pi * np.arange(200) / 200.0 |
| 3343 |
data1.shape = (100, 2) |
| 3344 |
data1[:, 1] = np.sin(data1[:, 0]) |
| 3345 |
markers1 = PolyMarker( |
| 3346 |
data1, legend="Green Markers", colour="green", marker="circle", size=1 |
| 3347 |
) |
| 3348 |
|
| 3349 |
# 50 points cos function, plotted as red line |
| 3350 |
data1 = 2.0 * np.pi * np.arange(100) / 100.0 |
| 3351 |
data1.shape = (50, 2) |
| 3352 |
data1[:, 1] = np.cos(data1[:, 0]) |
| 3353 |
lines = PolySpline(data1, legend="Red Line", colour="red") |
| 3354 |
|
| 3355 |
# A few more points... |
| 3356 |
pi = np.pi |
| 3357 |
markers2 = PolyMarker( |
| 3358 |
[(0.0, 0.0), (pi / 4.0, 1.0), (pi / 2, 0.0), (3.0 * pi / 4.0, -1)], |
| 3359 |
legend="Cross Legend", |
| 3360 |
colour="blue", |
| 3361 |
marker="cross", |
| 3362 |
) |
| 3363 |
|
| 3364 |
return PlotGraphics([markers1, lines, markers2], "Graph Title", "X Axis", "Y Axis") |
| 3365 |
|
| 3366 |
|
| 3367 |
def _draw2Objects(): |
| 3368 |
"""Draw a plot with two lines and a marker. |
| 3369 |
|
| 3370 |
Returns: |
| 3371 |
PlotGraphics: A plot with two lines and a marker. |
| 3372 |
""" |
| 3373 |
# 100 points sin function, plotted as green dots |
| 3374 |
data1 = 2.0 * np.pi * np.arange(200) / 200.0 |
| 3375 |
data1.shape = (100, 2) |
| 3376 |
data1[:, 1] = np.sin(data1[:, 0]) |
| 3377 |
line1 = PolySpline( |
| 3378 |
data1, legend="Green Line", colour="green", width=6, style=wx.PENSTYLE_DOT |
| 3379 |
) |
| 3380 |
|
| 3381 |
# 50 points cos function, plotted as red dot-dash |
| 3382 |
data1 = 2.0 * np.pi * np.arange(100) / 100.0 |
| 3383 |
data1.shape = (50, 2) |
| 3384 |
data1[:, 1] = np.cos(data1[:, 0]) |
| 3385 |
line2 = PolySpline( |
| 3386 |
data1, legend="Red Line", colour="red", width=3, style=wx.PENSTYLE_DOT_DASH |
| 3387 |
) |
| 3388 |
|
| 3389 |
# A few more points... |
| 3390 |
pi = np.pi |
| 3391 |
markers1 = PolyMarker( |
| 3392 |
[(0.0, 0.0), (pi / 4.0, 1.0), (pi / 2, 0.0), (3.0 * pi / 4.0, -1)], |
| 3393 |
legend="Cross Hatch Square", |
| 3394 |
colour="blue", |
| 3395 |
width=3, |
| 3396 |
size=6, |
| 3397 |
fillcolour="red", |
| 3398 |
fillstyle=wx.BRUSHSTYLE_CROSSDIAG_HATCH, |
| 3399 |
marker="square", |
| 3400 |
) |
| 3401 |
|
| 3402 |
return PlotGraphics( |
| 3403 |
[markers1, line1, line2], "Big Markers with Different Line Styles" |
| 3404 |
) |
| 3405 |
|
| 3406 |
|
| 3407 |
def _draw3Objects(): |
| 3408 |
"""Draw a plot with a selection of markers. |
| 3409 |
|
| 3410 |
Returns: |
| 3411 |
PlotGraphics: A plot with a selection of markers. |
| 3412 |
""" |
| 3413 |
markerList = [ |
| 3414 |
"circle", |
| 3415 |
"dot", |
| 3416 |
"square", |
| 3417 |
"triangle", |
| 3418 |
"triangle_down", |
| 3419 |
"cross", |
| 3420 |
"plus", |
| 3421 |
"circle", |
| 3422 |
] |
| 3423 |
m = [ |
| 3424 |
PolyMarker( |
| 3425 |
[(2 * i + 0.5, i + 0.5)], |
| 3426 |
legend=markerList[i], |
| 3427 |
colour="blue", |
| 3428 |
marker=markerList[i], |
| 3429 |
) |
| 3430 |
for i in range(len(markerList)) |
| 3431 |
] |
| 3432 |
return PlotGraphics(m, "Selection of Markers", "Minimal Axis", "No Axis") |
| 3433 |
|
| 3434 |
|
| 3435 |
def _draw4Objects(): |
| 3436 |
"""Draw a plot with 25,000 points and a line. |
| 3437 |
|
| 3438 |
Returns: |
| 3439 |
PlotGraphics: A plot with 25,000 points and a line. |
| 3440 |
""" |
| 3441 |
# 25,000 point line |
| 3442 |
data1 = np.arange(5e5, 1e6, 10) |
| 3443 |
data1.shape = (25000, 2) |
| 3444 |
line1 = PolyLine(data1, legend="Wide Line", colour="green", width=5) |
| 3445 |
|
| 3446 |
# A few more points... |
| 3447 |
markers2 = PolyMarker(data1, legend="Square", colour="blue", marker="square") |
| 3448 |
return PlotGraphics([line1, markers2], "25,000 Points", "Value X", "") |
| 3449 |
|
| 3450 |
|
| 3451 |
def _draw5Objects(): |
| 3452 |
"""Draw an empty plot with just axes. |
| 3453 |
|
| 3454 |
Returns: |
| 3455 |
PlotGraphics: An empty plot with axes defined but no points or lines. |
| 3456 |
""" |
| 3457 |
# Empty graph with axis defined but no points/lines |
| 3458 |
points = [] |
| 3459 |
line1 = PolyLine(points, legend="Wide Line", colour="green", width=5) |
| 3460 |
return PlotGraphics([line1], "Empty Plot With Just Axes", "Value X", "Value Y") |
| 3461 |
|
| 3462 |
|
| 3463 |
def _draw6Objects(): |
| 3464 |
"""Draw a bar graph with 6 bars, each a different colour. |
| 3465 |
|
| 3466 |
Returns: |
| 3467 |
PlotGraphics: A bar graph with 6 bars, each a different colour. |
| 3468 |
""" |
| 3469 |
# Bar graph |
| 3470 |
points1 = [(1, 0), (1, 10)] |
| 3471 |
line1 = PolyLine(points1, colour="green", legend="Feb.", width=10) |
| 3472 |
points1g = [(2, 0), (2, 4)] |
| 3473 |
line1g = PolyLine(points1g, colour="red", legend="Mar.", width=10) |
| 3474 |
points1b = [(3, 0), (3, 6)] |
| 3475 |
line1b = PolyLine(points1b, colour="blue", legend="Apr.", width=10) |
| 3476 |
|
| 3477 |
points2 = [(4, 0), (4, 12)] |
| 3478 |
line2 = PolyLine(points2, colour="Yellow", legend="May", width=10) |
| 3479 |
points2g = [(5, 0), (5, 8)] |
| 3480 |
line2g = PolyLine(points2g, colour="orange", legend="June", width=10) |
| 3481 |
points2b = [(6, 0), (6, 4)] |
| 3482 |
line2b = PolyLine(points2b, colour="brown", legend="July", width=10) |
| 3483 |
|
| 3484 |
return PlotGraphics( |
| 3485 |
[line1, line1g, line1b, line2, line2g, line2b], |
| 3486 |
"Bar Graph - (Turn on Grid, Legend)", |
| 3487 |
"Months", |
| 3488 |
"Number of Students", |
| 3489 |
) |
| 3490 |
|
| 3491 |
|
| 3492 |
def _draw7Objects(): |
| 3493 |
"""Draw a double log plot with two lines. |
| 3494 |
|
| 3495 |
Returns: |
| 3496 |
PlotGraphics: A double log plot with two lines, one quadratic and one cubic. |
| 3497 |
""" |
| 3498 |
# Empty graph with axis defined but no points/lines |
| 3499 |
x = np.arange(1, 1000, 1) |
| 3500 |
y1 = 4.5 * x**2 |
| 3501 |
y2 = 2.2 * x**3 |
| 3502 |
points1 = np.transpose([x, y1]) |
| 3503 |
points2 = np.transpose([x, y2]) |
| 3504 |
line1 = PolyLine(points1, legend="quadratic", colour="blue", width=1) |
| 3505 |
line2 = PolyLine(points2, legend="cubic", colour="red", width=1) |
| 3506 |
return PlotGraphics([line1, line2], "double log plot", "Value X", "Value Y") |
| 3507 |
|
| 3508 |
|
| 3509 |
class TestFrame(wx.Frame): |
| 3510 |
"""The main frame for the wxPython demo. |
| 3511 |
|
| 3512 |
Args: |
| 3513 |
parent (wx.Window): The parent window. |
| 3514 |
id (int): The identifier for the frame. |
| 3515 |
title (str): The title of the frame. |
| 3516 |
""" |
| 3517 |
|
| 3518 |
def __init__(self, parent, id, title): # noqa: A002 |
| 3519 |
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (600, 400)) |
| 3520 |
|
| 3521 |
# Now Create the menu bar and items |
| 3522 |
self.mainmenu = wx.MenuBar() |
| 3523 |
|
| 3524 |
menu = wx.Menu() |
| 3525 |
menu.Append(200, "Page Setup...", "Setup the printer page") |
| 3526 |
self.Bind(wx.EVT_MENU, self.OnFilePageSetup, id=200) |
| 3527 |
|
| 3528 |
menu.Append(201, "Print Preview...", "Show the current plot on page") |
| 3529 |
self.Bind(wx.EVT_MENU, self.OnFilePrintPreview, id=201) |
| 3530 |
|
| 3531 |
menu.Append(202, "Print...", "Print the current plot") |
| 3532 |
self.Bind(wx.EVT_MENU, self.OnFilePrint, id=202) |
| 3533 |
|
| 3534 |
menu.Append(203, "Save Plot...", "Save current plot") |
| 3535 |
self.Bind(wx.EVT_MENU, self.OnSaveFile, id=203) |
| 3536 |
|
| 3537 |
menu.Append(205, "E&xit", "Enough of this already!") |
| 3538 |
self.Bind(wx.EVT_MENU, self.OnFileExit, id=205) |
| 3539 |
self.mainmenu.Append(menu, "&File") |
| 3540 |
|
| 3541 |
menu = wx.Menu() |
| 3542 |
menu.Append(206, "Draw1", "Draw plots1") |
| 3543 |
self.Bind(wx.EVT_MENU, self.OnPlotDraw1, id=206) |
| 3544 |
menu.Append(207, "Draw2", "Draw plots2") |
| 3545 |
self.Bind(wx.EVT_MENU, self.OnPlotDraw2, id=207) |
| 3546 |
menu.Append(208, "Draw3", "Draw plots3") |
| 3547 |
self.Bind(wx.EVT_MENU, self.OnPlotDraw3, id=208) |
| 3548 |
menu.Append(209, "Draw4", "Draw plots4") |
| 3549 |
self.Bind(wx.EVT_MENU, self.OnPlotDraw4, id=209) |
| 3550 |
menu.Append(210, "Draw5", "Draw plots5") |
| 3551 |
self.Bind(wx.EVT_MENU, self.OnPlotDraw5, id=210) |
| 3552 |
menu.Append(260, "Draw6", "Draw plots6") |
| 3553 |
self.Bind(wx.EVT_MENU, self.OnPlotDraw6, id=260) |
| 3554 |
menu.Append(261, "Draw7", "Draw plots7") |
| 3555 |
self.Bind(wx.EVT_MENU, self.OnPlotDraw7, id=261) |
| 3556 |
|
| 3557 |
menu.Append(211, "&Redraw", "Redraw plots") |
| 3558 |
self.Bind(wx.EVT_MENU, self.OnPlotRedraw, id=211) |
| 3559 |
menu.Append(212, "&Clear", "Clear canvas") |
| 3560 |
self.Bind(wx.EVT_MENU, self.OnPlotClear, id=212) |
| 3561 |
menu.Append(213, "&Scale", "Scale canvas") |
| 3562 |
self.Bind(wx.EVT_MENU, self.OnPlotScale, id=213) |
| 3563 |
menu.Append(214, "Enable &Zoom", "Enable Mouse Zoom", kind=wx.ITEM_CHECK) |
| 3564 |
self.Bind(wx.EVT_MENU, self.OnEnableZoom, id=214) |
| 3565 |
menu.Append(215, "Enable &Grid", "Turn on Grid", kind=wx.ITEM_CHECK) |
| 3566 |
self.Bind(wx.EVT_MENU, self.OnEnableGrid, id=215) |
| 3567 |
menu.Append(217, "Enable &Drag", "Activates dragging mode", kind=wx.ITEM_CHECK) |
| 3568 |
self.Bind(wx.EVT_MENU, self.OnEnableDrag, id=217) |
| 3569 |
menu.Append(220, "Enable &Legend", "Turn on Legend", kind=wx.ITEM_CHECK) |
| 3570 |
self.Bind(wx.EVT_MENU, self.OnEnableLegend, id=220) |
| 3571 |
menu.Append( |
| 3572 |
222, "Enable &Point Label", "Show Closest Point", kind=wx.ITEM_CHECK |
| 3573 |
) |
| 3574 |
self.Bind(wx.EVT_MENU, self.OnEnablePointLabel, id=222) |
| 3575 |
|
| 3576 |
menu.Append(223, "Enable &Anti-Aliasing", "Smooth output", kind=wx.ITEM_CHECK) |
| 3577 |
self.Bind(wx.EVT_MENU, self.OnEnableAntiAliasing, id=223) |
| 3578 |
menu.Append( |
| 3579 |
224, |
| 3580 |
"Enable &High-Resolution AA", |
| 3581 |
"Draw in higher resolution", |
| 3582 |
kind=wx.ITEM_CHECK, |
| 3583 |
) |
| 3584 |
self.Bind(wx.EVT_MENU, self.OnEnableHiRes, id=224) |
| 3585 |
|
| 3586 |
menu.Append(226, "Enable Center Lines", "Draw center lines", kind=wx.ITEM_CHECK) |
| 3587 |
self.Bind(wx.EVT_MENU, self.OnEnableCenterLines, id=226) |
| 3588 |
menu.Append( |
| 3589 |
227, "Enable Diagonal Lines", "Draw diagonal lines", kind=wx.ITEM_CHECK |
| 3590 |
) |
| 3591 |
self.Bind(wx.EVT_MENU, self.OnEnableDiagonals, id=227) |
| 3592 |
|
| 3593 |
menu.Append(231, "Set Gray Background", "Change background colour to gray") |
| 3594 |
self.Bind(wx.EVT_MENU, self.OnBackgroundGray, id=231) |
| 3595 |
menu.Append(232, "Set &White Background", "Change background colour to white") |
| 3596 |
self.Bind(wx.EVT_MENU, self.OnBackgroundWhite, id=232) |
| 3597 |
menu.Append(233, "Set Red Label Text", "Change label text colour to red") |
| 3598 |
self.Bind(wx.EVT_MENU, self.OnForegroundRed, id=233) |
| 3599 |
menu.Append(234, "Set &Black Label Text", "Change label text colour to black") |
| 3600 |
self.Bind(wx.EVT_MENU, self.OnForegroundBlack, id=234) |
| 3601 |
|
| 3602 |
menu.Append(225, "Scroll Up 1", "Move View Up 1 Unit") |
| 3603 |
self.Bind(wx.EVT_MENU, self.OnScrUp, id=225) |
| 3604 |
menu.Append(230, "Scroll Rt 2", "Move View Right 2 Units") |
| 3605 |
self.Bind(wx.EVT_MENU, self.OnScrRt, id=230) |
| 3606 |
menu.Append(235, "&Plot Reset", "Reset to original plot") |
| 3607 |
self.Bind(wx.EVT_MENU, self.OnReset, id=235) |
| 3608 |
|
| 3609 |
self.mainmenu.Append(menu, "&Plot") |
| 3610 |
|
| 3611 |
menu = wx.Menu() |
| 3612 |
menu.Append(300, "&About", "About this thing...") |
| 3613 |
self.Bind(wx.EVT_MENU, self.OnHelpAbout, id=300) |
| 3614 |
self.mainmenu.Append(menu, "&Help") |
| 3615 |
|
| 3616 |
self.SetMenuBar(self.mainmenu) |
| 3617 |
|
| 3618 |
# A status bar to tell people what's happening |
| 3619 |
self.CreateStatusBar(1) |
| 3620 |
|
| 3621 |
self.client = PlotCanvas(self) |
| 3622 |
# define the function for drawing pointLabels |
| 3623 |
self.client.SetPointLabelFunc(self.DrawPointLabel) |
| 3624 |
# Create mouse event for showing cursor coords in status bar |
| 3625 |
self.client.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown) |
| 3626 |
# Show closest point when enabled |
| 3627 |
self.client.canvas.Bind(wx.EVT_MOTION, self.OnMotion) |
| 3628 |
|
| 3629 |
self.Show(True) |
| 3630 |
|
| 3631 |
def DrawPointLabel(self, dc, mDataDict): |
| 3632 |
"""Define how the pointLabels are plotted. |
| 3633 |
|
| 3634 |
As an example I have decided I want a box at the curve point |
| 3635 |
with some text information about the curve plotted below. |
| 3636 |
Any wxDC method can be used. |
| 3637 |
|
| 3638 |
Args: |
| 3639 |
dc: DC that will be passed. |
| 3640 |
mDataDict (dict): Dictionary of data that you want to use for the |
| 3641 |
pointLabel |
| 3642 |
|
| 3643 |
""" |
| 3644 |
# ---------- |
| 3645 |
dc.SetPen(wx.Pen(wx.BLACK)) |
| 3646 |
dc.SetBrush(wx.Brush(wx.BLACK, wx.BRUSHSTYLE_SOLID)) |
| 3647 |
|
| 3648 |
sx, sy = mDataDict["scaledXY"] # scaled x,y of closest point |
| 3649 |
dc.DrawRectangle(sx - 5, sy - 5, 10, 10) # 10by10 square centered on point |
| 3650 |
px, py = mDataDict["pointXY"] |
| 3651 |
cNum = mDataDict["curveNum"] |
| 3652 |
pntIn = mDataDict["pIndex"] |
| 3653 |
legend = mDataDict["legend"] |
| 3654 |
# make a string to display |
| 3655 |
s = f"Crv# {cNum}, '{legend}', Pt. ({px:.2f},{py:.2f}), PtInd {pntIn}" |
| 3656 |
dc.DrawText(s, int(sx), int(sy + 1)) |
| 3657 |
# ----------- |
| 3658 |
|
| 3659 |
def OnMouseLeftDown(self, event): |
| 3660 |
"""Handle left mouse button down events to show coordinates in status bar. |
| 3661 |
|
| 3662 |
Args: |
| 3663 |
event (wx.Event): The event that triggered this method. |
| 3664 |
""" |
| 3665 |
s = "Left Mouse Down at Point: ({:.4f}, {:.4f})".format( |
| 3666 |
*self.client._getXY(event) |
| 3667 |
) |
| 3668 |
self.SetStatusText(s) |
| 3669 |
event.Skip() # allows plotCanvas OnMouseLeftDown to be called |
| 3670 |
|
| 3671 |
def OnMotion(self, event): |
| 3672 |
"""Handle mouse motion events to show closest point if enabled. |
| 3673 |
|
| 3674 |
Args: |
| 3675 |
event (wx.Event): The event that triggered this method. |
| 3676 |
""" |
| 3677 |
# show closest point (when enbled) |
| 3678 |
if self.client.GetEnablePointLabel(): |
| 3679 |
# make up dict with info for the pointLabel |
| 3680 |
# I've decided to mark the closest point on the closest curve |
| 3681 |
dlst = self.client.GetClosestPoint( |
| 3682 |
self.client._getXY(event), pointScaled=True |
| 3683 |
) |
| 3684 |
if dlst: # returns [] if none |
| 3685 |
curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst |
| 3686 |
# make up dictionary to pass to my user function (see DrawPointLabel) |
| 3687 |
mDataDict = { |
| 3688 |
"curveNum": curveNum, |
| 3689 |
"legend": legend, |
| 3690 |
"pIndex": pIndex, |
| 3691 |
"pointXY": pointXY, |
| 3692 |
"scaledXY": scaledXY, |
| 3693 |
} |
| 3694 |
# pass dict to update the pointLabel |
| 3695 |
self.client.UpdatePointLabel(mDataDict) |
| 3696 |
event.Skip() # go to next handler |
| 3697 |
|
| 3698 |
def OnFilePageSetup(self, event): |
| 3699 |
"""Setup the printer page. |
| 3700 |
|
| 3701 |
Args: |
| 3702 |
event (wx.Event): The event that triggered this method. |
| 3703 |
""" |
| 3704 |
self.client.PageSetup() |
| 3705 |
|
| 3706 |
def OnFilePrintPreview(self, event): |
| 3707 |
"""Show the current plot in a print preview. |
| 3708 |
|
| 3709 |
Args: |
| 3710 |
event (wx.Event): The event that triggered this method. |
| 3711 |
""" |
| 3712 |
self.client.PrintPreview() |
| 3713 |
|
| 3714 |
def OnFilePrint(self, event): |
| 3715 |
"""Print the current plot. |
| 3716 |
|
| 3717 |
Args: |
| 3718 |
event (wx.Event): The event that triggered this method. |
| 3719 |
""" |
| 3720 |
self.client.Printout() |
| 3721 |
|
| 3722 |
def OnSaveFile(self, event): |
| 3723 |
"""Save the current plot to a file. |
| 3724 |
|
| 3725 |
Args: |
| 3726 |
event (wx.Event): The event that triggered this method. |
| 3727 |
""" |
| 3728 |
self.client.SaveFile() |
| 3729 |
|
| 3730 |
def OnFileExit(self, event): |
| 3731 |
"""Exit the application. |
| 3732 |
|
| 3733 |
Args: |
| 3734 |
event (wx.Event): The event that triggered this method. |
| 3735 |
""" |
| 3736 |
self.Close() |
| 3737 |
|
| 3738 |
def OnPlotDraw1(self, event): |
| 3739 |
"""Draw a plot with different markers and lines. |
| 3740 |
|
| 3741 |
Args: |
| 3742 |
event (wx.Event): The event that triggered this method. |
| 3743 |
""" |
| 3744 |
self.resetDefaults() |
| 3745 |
self.client.Draw(_draw1Objects()) |
| 3746 |
|
| 3747 |
def OnPlotDraw2(self, event): |
| 3748 |
"""Draw a plot with different line styles. |
| 3749 |
|
| 3750 |
Args: |
| 3751 |
event (wx.Event): The event that triggered this method. |
| 3752 |
""" |
| 3753 |
self.resetDefaults() |
| 3754 |
self.client.Draw(_draw2Objects()) |
| 3755 |
|
| 3756 |
def OnPlotDraw3(self, event): |
| 3757 |
"""Draw a plot with different markers. |
| 3758 |
|
| 3759 |
Args: |
| 3760 |
event (wx.Event): The event that triggered this method. |
| 3761 |
""" |
| 3762 |
self.resetDefaults() |
| 3763 |
self.client.SetFont( |
| 3764 |
wx.Font( |
| 3765 |
10, wx.FONTFAMILY_SCRIPT, wx.FONTWEIGHT_NORMAL, wx.FONTWEIGHT_NORMAL |
| 3766 |
) |
| 3767 |
) |
| 3768 |
self.client.SetFontSizeAxis(20) |
| 3769 |
self.client.SetFontSizeLegend(12) |
| 3770 |
self.client.SetXSpec("min") |
| 3771 |
self.client.SetYSpec("none") |
| 3772 |
self.client.Draw(_draw3Objects()) |
| 3773 |
|
| 3774 |
def OnPlotDraw4(self, event): |
| 3775 |
"""Draw a plot with 25,000 points. |
| 3776 |
|
| 3777 |
Args: |
| 3778 |
event (wx.Event): The event that triggered this method. |
| 3779 |
""" |
| 3780 |
self.resetDefaults() |
| 3781 |
drawObj = _draw4Objects() |
| 3782 |
self.client.Draw(drawObj) |
| 3783 |
|
| 3784 |
# # profile |
| 3785 |
# start = _time.time() |
| 3786 |
# for x in range(10): |
| 3787 |
# self.client.Draw(drawObj) |
| 3788 |
# print "10 plots of Draw4 took: %f sec."%(_time.time() - start) |
| 3789 |
# # profile end |
| 3790 |
|
| 3791 |
def OnPlotDraw5(self, event): |
| 3792 |
"""Draw an empty plot with just axes. |
| 3793 |
|
| 3794 |
Args: |
| 3795 |
event (wx.Event): The event that triggered this method. |
| 3796 |
""" |
| 3797 |
# Empty plot with just axes |
| 3798 |
self.resetDefaults() |
| 3799 |
drawObj = _draw5Objects() |
| 3800 |
# make the axis X= (0,5), Y=(0,10) |
| 3801 |
# (default with None is X= (-1,1), Y= (-1,1)) |
| 3802 |
self.client.Draw(drawObj, xAxis=(0, 5), yAxis=(0, 10)) |
| 3803 |
|
| 3804 |
def OnPlotDraw6(self, event): |
| 3805 |
"""Draw a bar graph. |
| 3806 |
|
| 3807 |
Args: |
| 3808 |
event (wx.Event): The event that triggered this method. |
| 3809 |
""" |
| 3810 |
# Bar Graph Example |
| 3811 |
self.resetDefaults() |
| 3812 |
# self.client.SetEnableLegend(True) #turn on Legend |
| 3813 |
# self.client.SetEnableGrid(True) #turn on Grid |
| 3814 |
self.client.SetXSpec("none") # turns off x-axis scale |
| 3815 |
self.client.SetYSpec("auto") |
| 3816 |
self.client.Draw(_draw6Objects(), xAxis=(0, 7)) |
| 3817 |
|
| 3818 |
def OnPlotDraw7(self, event): |
| 3819 |
"""Draw a double log scale plot. |
| 3820 |
|
| 3821 |
Args: |
| 3822 |
event (wx.Event): The event that triggered this method. |
| 3823 |
""" |
| 3824 |
# log scale example |
| 3825 |
self.resetDefaults() |
| 3826 |
self.client.setLogScale((True, True)) |
| 3827 |
self.client.Draw(_draw7Objects()) |
| 3828 |
|
| 3829 |
def OnPlotRedraw(self, event): |
| 3830 |
"""Redraw the plot canvas. |
| 3831 |
|
| 3832 |
Args: |
| 3833 |
event (wx.Event): The event that triggered this method. |
| 3834 |
""" |
| 3835 |
self.client.Redraw() |
| 3836 |
|
| 3837 |
def OnPlotClear(self, event): |
| 3838 |
"""Clear the plot canvas. |
| 3839 |
|
| 3840 |
Args: |
| 3841 |
event (wx.Event): The event that triggered this method. |
| 3842 |
""" |
| 3843 |
self.client.Clear() |
| 3844 |
|
| 3845 |
def OnPlotScale(self, event): |
| 3846 |
"""Scale the plot to a specific range. |
| 3847 |
|
| 3848 |
Args: |
| 3849 |
event (wx.Event): The event that triggered this method. |
| 3850 |
""" |
| 3851 |
if self.client.last_draw is not None: |
| 3852 |
graphics, xAxis, yAxis = self.client.last_draw |
| 3853 |
self.client.Draw(graphics, (1, 3.05), (0, 1)) |
| 3854 |
|
| 3855 |
def OnEnableZoom(self, event): |
| 3856 |
"""Enable or disable zooming in the plot. |
| 3857 |
|
| 3858 |
Args: |
| 3859 |
event (wx.Event): The event that triggered this method. |
| 3860 |
""" |
| 3861 |
self.client.SetEnableZoom(event.IsChecked()) |
| 3862 |
self.mainmenu.Check(217, not event.IsChecked()) |
| 3863 |
|
| 3864 |
def OnEnableGrid(self, event): |
| 3865 |
"""Enable or disable the grid in the plot. |
| 3866 |
|
| 3867 |
Args: |
| 3868 |
event (wx.Event): The event that triggered this method. |
| 3869 |
""" |
| 3870 |
self.client.SetEnableGrid(event.IsChecked()) |
| 3871 |
|
| 3872 |
def OnEnableDrag(self, event): |
| 3873 |
"""Enable or disable dragging mode in the plot. |
| 3874 |
|
| 3875 |
Args: |
| 3876 |
event (wx.Event): The event that triggered this method. |
| 3877 |
""" |
| 3878 |
self.client.SetEnableDrag(event.IsChecked()) |
| 3879 |
self.mainmenu.Check(214, not event.IsChecked()) |
| 3880 |
|
| 3881 |
def OnEnableLegend(self, event): |
| 3882 |
"""Enable or disable the legend in the plot. |
| 3883 |
|
| 3884 |
Args: |
| 3885 |
event (wx.Event): The event that triggered this method. |
| 3886 |
""" |
| 3887 |
self.client.SetEnableLegend(event.IsChecked()) |
| 3888 |
|
| 3889 |
def OnEnablePointLabel(self, event): |
| 3890 |
"""Enable or disable point labels in the plot. |
| 3891 |
|
| 3892 |
Args: |
| 3893 |
event (wx.Event): The event that triggered this method. |
| 3894 |
""" |
| 3895 |
self.client.SetEnablePointLabel(event.IsChecked()) |
| 3896 |
|
| 3897 |
def OnEnableAntiAliasing(self, event): |
| 3898 |
"""Enable or disable anti-aliasing. |
| 3899 |
|
| 3900 |
Args: |
| 3901 |
event (wx.Event): The event that triggered this method. |
| 3902 |
""" |
| 3903 |
self.client.SetEnableAntiAliasing(event.IsChecked()) |
| 3904 |
|
| 3905 |
def OnEnableHiRes(self, event): |
| 3906 |
"""Enable or disable high-resolution anti-aliasing. |
| 3907 |
|
| 3908 |
Args: |
| 3909 |
event (wx.Event): The event that triggered this method. |
| 3910 |
""" |
| 3911 |
self.client.SetEnableHiRes(event.IsChecked()) |
| 3912 |
|
| 3913 |
def OnEnableCenterLines(self, event): |
| 3914 |
"""Enable or disable center lines in the plot. |
| 3915 |
|
| 3916 |
Args: |
| 3917 |
event (wx.Event): The event that triggered this method. |
| 3918 |
""" |
| 3919 |
self.client.SetEnableCenterLines(event.IsChecked()) |
| 3920 |
|
| 3921 |
def OnEnableDiagonals(self, event): |
| 3922 |
"""Enable or disable diagonal lines in the plot. |
| 3923 |
|
| 3924 |
Args: |
| 3925 |
event (wx.Event): The event that triggered this method. |
| 3926 |
""" |
| 3927 |
self.client.SetEnableDiagonals(event.IsChecked()) |
| 3928 |
|
| 3929 |
def OnBackgroundGray(self, event): |
| 3930 |
"""Change the background colour to gray. |
| 3931 |
|
| 3932 |
Args: |
| 3933 |
event (wx.Event): The event that triggered this method. |
| 3934 |
""" |
| 3935 |
self.client.SetBackgroundColour("#CCCCCC") |
| 3936 |
self.client.Redraw() |
| 3937 |
|
| 3938 |
def OnBackgroundWhite(self, event): |
| 3939 |
"""Change the background colour to white. |
| 3940 |
|
| 3941 |
Args: |
| 3942 |
event (wx.Event): The event that triggered this method. |
| 3943 |
""" |
| 3944 |
self.client.SetBackgroundColour("white") |
| 3945 |
self.client.Redraw() |
| 3946 |
|
| 3947 |
def OnForegroundRed(self, event): |
| 3948 |
"""Change the label text colour to red. |
| 3949 |
|
| 3950 |
Args: |
| 3951 |
event (wx.Event): The event that triggered this method. |
| 3952 |
""" |
| 3953 |
self.client.SetForegroundColour("red") |
| 3954 |
self.client.Redraw() |
| 3955 |
|
| 3956 |
def OnForegroundBlack(self, event): |
| 3957 |
"""Change the label text colour to black. |
| 3958 |
|
| 3959 |
Args: |
| 3960 |
event (wx.Event): The event that triggered this method. |
| 3961 |
""" |
| 3962 |
self.client.SetForegroundColour("black") |
| 3963 |
self.client.Redraw() |
| 3964 |
|
| 3965 |
def OnScrUp(self, event): |
| 3966 |
"""Scroll the plot up by 1 unit. |
| 3967 |
|
| 3968 |
Args: |
| 3969 |
event (wx.Event): The event that triggered this method. |
| 3970 |
""" |
| 3971 |
self.client.ScrollUp(1) |
| 3972 |
|
| 3973 |
def OnScrRt(self, event): |
| 3974 |
"""Scroll the plot to the right by 2 units. |
| 3975 |
|
| 3976 |
Args: |
| 3977 |
event (wx.Event): The event that triggered this method. |
| 3978 |
""" |
| 3979 |
self.client.ScrollRight(2) |
| 3980 |
|
| 3981 |
def OnReset(self, event): |
| 3982 |
"""Reset the plot to the original state. |
| 3983 |
|
| 3984 |
Args: |
| 3985 |
event (wx.Event): The event that triggered this method. |
| 3986 |
""" |
| 3987 |
self.client.Reset() |
| 3988 |
|
| 3989 |
def OnHelpAbout(self, event): |
| 3990 |
"""Show an about dialog with some information about the demo. |
| 3991 |
|
| 3992 |
Args: |
| 3993 |
event (wx.Event): The event that triggered this method. |
| 3994 |
""" |
| 3995 |
from wx.lib.dialogs import ScrolledMessageDialog |
| 3996 |
|
| 3997 |
about = ScrolledMessageDialog(self, __doc__, "About...") |
| 3998 |
about.ShowModal() |
| 3999 |
|
| 4000 |
def resetDefaults(self): |
| 4001 |
"""Just to reset the fonts back to the PlotCanvas defaults.""" |
| 4002 |
self.client.SetFont( |
| 4003 |
wx.Font(10, wx.FONTFAMILY_SWISS, wx.FONTWEIGHT_NORMAL, wx.FONTWEIGHT_NORMAL) |
| 4004 |
) |
| 4005 |
self.client.SetFontSizeAxis(10) |
| 4006 |
self.client.SetFontSizeLegend(7) |
| 4007 |
self.client.setLogScale((False, False)) |
| 4008 |
self.client.SetXSpec("auto") |
| 4009 |
self.client.SetYSpec("auto") |
| 4010 |
|
| 4011 |
|
| 4012 |
def __test(): |
| 4013 |
class MyApp(wx.App): |
| 4014 |
def OnInit(self): |
| 4015 |
wx.InitAllImageHandlers() |
| 4016 |
frame = TestFrame(None, -1, "PlotCanvas") |
| 4017 |
# frame.Show(True) |
| 4018 |
self.SetTopWindow(frame) |
| 4019 |
return True |
| 4020 |
|
| 4021 |
app = MyApp(0) |
| 4022 |
app.MainLoop() |
| 4023 |
|
| 4024 |
|
| 4025 |
if __name__ == "__main__": |
| 4026 |
__test() |