Skip to content

Commit 769843a

Browse files
committed
corrected a bug for legend display and log a warning
1 parent 5d27d91 commit 769843a

File tree

3 files changed

+69
-44
lines changed

3 files changed

+69
-44
lines changed

pygame_matplotlib/backend_pygame.py

Lines changed: 53 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from matplotlib.artist import Artist
1515
from matplotlib.pyplot import figure
1616
from matplotlib.axes import Axes
17+
from matplotlib.transforms import IdentityTransform
1718
import numpy as np
1819
from matplotlib.transforms import Affine2D
1920
import pygame
@@ -34,6 +35,18 @@
3435
from matplotlib.path import Path
3536
from matplotlib.transforms import Bbox
3637

38+
import logging
39+
40+
logger = logging.getLogger(__name__)
41+
console = logging.StreamHandler()
42+
logger.addHandler(console)
43+
44+
# logger.setLevel(logging.DEBUG)
45+
46+
logger.warning(
47+
f"{__name__} is still in developpement. Please see our github page."
48+
)
49+
3750

3851
class FigureSurface(pygame.Surface, Figure):
3952
"""Hybrid object mixing pygame.Surface and matplotlib.Figure.
@@ -69,18 +82,25 @@ def draw(self, renderer):
6982

7083
def set_alpha(self):
7184
pass
85+
7286
def set_at(self):
7387
pass
88+
7489
def set_clip(self):
7590
pass
91+
7692
def set_colorkey(self):
7793
pass
94+
7895
def set_masks(self):
7996
pass
97+
8098
def set_palette(self):
8199
pass
100+
82101
def set_palette_at(self):
83102
pass
103+
84104
def set_shifts(self):
85105
pass
86106

@@ -162,16 +182,18 @@ def draw_path(self, gc, path, transform, rgbFace=None):
162182
transfrom_to_pygame_axis.set_matrix(
163183
[[1, 0, 0], [0, -1, self.surface.get_height()], [0, 0, 1]]
164184
)
165-
166-
transform += transfrom_to_pygame_axis
185+
if not isinstance(transform, IdentityTransform):
186+
transform += transfrom_to_pygame_axis
167187

168188
draw_func = ( # Select whether antialiased will be used in pygame
169189
pygame.draw.aaline if gc.get_antialiased() else pygame.draw.line
170190
)
171191

172192
previous_point = (0, 0)
173193
poly_points = []
194+
174195
for point, code in path.iter_segments(transform):
196+
logger.debug(point, code)
175197
if code == Path.LINETO:
176198
draw_func(
177199
self.surface, color, previous_point, point, linewidth
@@ -248,41 +270,38 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
248270
# Get the expected size of the font
249271
width, height = myfont.size(s)
250272
# Tuple for the position of the font
251-
font_surf_position = (
252-
x,
253-
self.surface.get_height() - y
254-
)
273+
font_surf_position = (x, self.surface.get_height() - y)
255274
if mtext is not None:
256275
# Use the alignement from mtext or default
257276
h_alignment = mtext.get_horizontalalignment()
258277
v_alignment = mtext.get_verticalalignment()
259278
else:
260-
h_alignment = 'center'
261-
v_alignment = 'center'
279+
h_alignment = "center"
280+
v_alignment = "center"
262281
# Use the alignement to know where the font should go
263-
if h_alignment == 'left':
282+
if h_alignment == "left":
264283
h_offset = 0
265-
elif h_alignment == 'center':
266-
h_offset = - width / 2
267-
elif h_alignment == 'right':
268-
h_offset = - width
284+
elif h_alignment == "center":
285+
h_offset = -width / 2
286+
elif h_alignment == "right":
287+
h_offset = -width
269288
else:
270289
h_offset = 0
271290

272-
if v_alignment == 'top':
291+
if v_alignment == "top":
273292
v_offset = 0
274-
elif v_alignment == 'center' or v_alignment == 'center_baseline':
275-
v_offset = - height / 2
276-
elif v_alignment == 'bottom' or v_alignment == 'baseline':
277-
v_offset = - height
293+
elif v_alignment == "center" or v_alignment == "center_baseline":
294+
v_offset = -height / 2
295+
elif v_alignment == "bottom" or v_alignment == "baseline":
296+
v_offset = -height
278297
else:
279298
v_offset = 0
280299
# pygame.draw.circle(self.surface, (255, 0, 0), (x, self.surface.get_height() - y), 3)
281300
# pygame.draw.lines(self.surface, (0, 255, 0), True, ((x, self.surface.get_height() - y), (x + width, self.surface.get_height() - y), (x + width, self.surface.get_height() - y + height)))
282301
# Tuple for the position of the font
283302
font_surf_position = (
284303
x + h_offset,
285-
self.surface.get_height() - y + v_offset
304+
self.surface.get_height() - y + v_offset,
286305
)
287306
self.surface.blit(font_surface, font_surf_position)
288307

@@ -318,8 +337,6 @@ def copy_from_bbox(self, bbox):
318337
return copy
319338

320339

321-
322-
323340
class GraphicsContextPygame(GraphicsContextBase):
324341
"""
325342
The graphics context provides the color, line styles, etc... See the cairo
@@ -405,6 +422,7 @@ class methods button_press_event, button_release_event,
405422
figure : `matplotlib.figure.Figure`
406423
A high-level Figure instance
407424
"""
425+
408426
blitting: bool = False
409427

410428
# File types allowed for saving
@@ -433,9 +451,10 @@ def copy_from_bbox(self, bbox):
433451

434452
def restore_region(self, region, bbox=None, xy=None):
435453
rect = (
436-
pygame.Rect(*(
437-
0, 0 if xy is None else xy
438-
), *self.get_renderer().surface.get_size())
454+
pygame.Rect(
455+
*(0, 0 if xy is None else xy),
456+
*self.get_renderer().surface.get_size(),
457+
)
439458
if bbox is None
440459
else self.rect_from_bbox(bbox)
441460
)
@@ -461,14 +480,11 @@ def draw(self):
461480
# Full redraw of the figure
462481
self.figure.draw(self.renderer)
463482

464-
465483
def blit(self, bbox=None):
466484
self.renderer = self.get_renderer(cleared=False)
467485
self.renderer.surface = self.figure
468486
self.blitting = True
469487

470-
471-
472488
def get_renderer(self, cleared=False) -> RendererPygame:
473489
fig = self.figure
474490
reuse_renderer = (
@@ -507,7 +523,7 @@ def start_event_loop(self, interval: float):
507523
time_elapsed = 0
508524
while time_elapsed < interval:
509525
events = pygame.event.get()
510-
time_elapsed += FramePerSec.tick(FPS) / 1000. # Convert ms
526+
time_elapsed += FramePerSec.tick(FPS) / 1000.0 # Convert ms
511527
for event in events:
512528
if event.type == pygame.QUIT:
513529
pygame.quit()
@@ -519,20 +535,25 @@ class FigureManagerPygame(FigureManagerBase):
519535
520536
For non-interactive backends, the base class is sufficient.
521537
"""
538+
522539
canvas: FigureCanvasPygame
540+
523541
def get_main_display(self):
524-
if hasattr(self.canvas, 'main_display'):
525-
if (self.canvas.figure.get_size() == self.canvas.main_display.get_size()):
542+
if hasattr(self.canvas, "main_display"):
543+
if (
544+
self.canvas.figure.get_size()
545+
== self.canvas.main_display.get_size()
546+
):
526547
# If the main display exist and its size has not changed
527548
return self.canvas.main_display
528549
main_display = pygame.display.set_mode(
529550
self.canvas.figure.get_size(), # Size matches figure size
530551
)
531-
main_display.fill('white')
552+
main_display.fill("white")
532553
self.canvas.main_display = main_display
533554
return main_display
534555

535-
def show(self, block):
556+
def show(self, block=True):
536557
# do something to display the GUI
537558
pygame.init()
538559
main_display = self.get_main_display()

pygame_matplotlib/gui_window.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88

99
from .backend_pygame import FigureSurface
1010
import matplotlib
11-
matplotlib.use('module://pygame_matplotlib.backend_pygame')
11+
12+
matplotlib.use("module://pygame_matplotlib.backend_pygame")
13+
1214

1315
class UIPlotWindow(pygame_gui.elements.ui_window.UIWindow):
1416
def __init__(
@@ -20,23 +22,23 @@ def __init__(
2022
element_id: Union[str, None] = None,
2123
object_id: Union[ObjectID, str, None] = None,
2224
resizable: bool = False,
23-
visible: int = 1
25+
visible: int = 1,
2426
):
2527
self.figuresurf = figuresurface
2628
super().__init__(
27-
rect, manager,
29+
rect,
30+
manager,
2831
window_display_title=window_display_title,
2932
element_id=element_id,
3033
object_id=object_id,
3134
resizable=resizable,
32-
visible=visible
35+
visible=visible,
3336
)
3437

3538
def set_dimensions(self, *args, **kwargs):
3639
super().set_dimensions(*args, **kwargs)
40+
print("setting dimensions")
3741
# Update the size of the figure with the new bounding rectangle
38-
self.figuresurf.set_bounding_rect(
39-
self.get_container().get_rect()
40-
)
42+
self.figuresurf.set_bounding_rect(self.get_container().get_rect())
4143
# Update the image of the container
4244
self.get_container().set_image(self.figuresurf)

test_plt.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,18 @@
44
import pygame
55

66
import matplotlib
7-
matplotlib.use('module://pygame_matplotlib.backend_pygame')
7+
8+
matplotlib.use("module://pygame_matplotlib.backend_pygame")
89
# matplotlib.use('Qt4Agg')
910

1011
import matplotlib.pyplot as plt
1112
import matplotlib.figure as fg
1213

13-
14-
plt.plot([1,2], [1,2], color='green')
15-
plt.text(1.5, 1.5, '2', size=50)
16-
plt.xlabel('swag')
14+
plt.figure(figsize=(16, 9))
15+
plt.plot([1, 2], [1, 2], color="green", label="HAHA")
16+
plt.text(1.5, 1.5, "2", size=50)
17+
plt.xlabel("swag")
18+
plt.legend()
1719

1820

1921
plt.show()

0 commit comments

Comments
 (0)