Skip to content

Commit

Permalink
Add functions for setting a ternary specific background color
Browse files Browse the repository at this point in the history
  • Loading branch information
marcharper committed Feb 17, 2021
1 parent d834330 commit c3a00e2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
9 changes: 9 additions & 0 deletions ternary/heatmapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,3 +409,12 @@ def svg_heatmap(data, scale, filename, vmax=None, vmin=None, style='h',
output_file.write(svg_polygon(vertices, color))

output_file.write('</svg>\n')


def background_color(ax, color, scale, zorder=-1000, alpha=None):
"""Draws a triangle behind the plot to serve as the background color."""
vertices = [(scale, 0, 0), (0, scale, 0), (0, 0, scale)]
vertices = map(project_point, vertices)
xs, ys = unzip(vertices)
poly = ax.fill(xs, ys, facecolor=color, edgecolor=color, zorder=zorder, alpha=alpha)
return poly
26 changes: 26 additions & 0 deletions ternary/ternary_axes_subplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Wrapper class for all ternary plotting functions.
"""

from collections import namedtuple
from functools import partial

import numpy
Expand All @@ -13,6 +14,9 @@
from .helpers import project_point, convert_coordinates_sequence


BackgroundParameters = namedtuple('BackgroundParameters', ['color', 'alpha', 'zorder'])


def figure(ax=None, scale=None, permutation=None):
"""
Wraps a Matplotlib AxesSubplot or generates a new one. Emulates matplotlib's
Expand Down Expand Up @@ -70,6 +74,11 @@ def __init__(self, ax=None, scale=None, permutation=None):
# Container for the redrawing of labels
self._to_remove = []
self._connect_callbacks()
# Background
self._background_parameters = None
# Cache for the background triangle object, so it can be removed and redrawn as needed.
self._background_triangle = None
self.set_background_color(color="whitesmoke", zorder=-1000, alpha=0.75)

def _connect_callbacks(self):
"""Connect resize matplotlib callbacks."""
Expand Down Expand Up @@ -454,3 +463,20 @@ def heatmapf(self, func, scale=None, cmap=None, boundary=True,
colorbar=colorbar, permutation=permutation,
vmin=vmin, vmax=vmax, cbarlabel=cbarlabel,
cb_kwargs=cb_kwargs)

def set_background_color(self, color="whitesmoke", zorder=-1000, alpha=0.75):
self._background_parameters = BackgroundParameters(color=color, alpha=alpha, zorder=zorder)
self._draw_background()

def _draw_background(self):
color, alpha, zorder = self._background_parameters
scale = self.get_scale()
ax = self.get_axes()

# Remove any existing background
if self._background_triangle:
print(self._background_triangle)
self._background_triangle.remove()

# Draw the background
self._background_triangle = heatmapping.background_color(ax, color, scale, alpha=alpha, zorder=zorder)[0]

0 comments on commit c3a00e2

Please sign in to comment.