Beispiel #1
0
    def from_legend(cls, legend):
        if not (legend and legend.get_texts()):
            return None

        props = dict()

        props['visible'] = legend.get_visible()

        title = legend.get_title()
        if isinstance(title.get_text(), str):
            props['title'] = title.get_text()
        else:
            props['title'] = None

        # For Matplotlib <3.2 we have to remove the 'None' string from the title
        # which is generated by set_text() in text.py
        if props['title'] == 'None':
            props['title'] = ''

        props['title_font'] = title.get_fontname()
        props['title_size'] = title.get_fontsize()
        props['title_color'] = convert_color_to_hex(title.get_color())

        props['box_visible'] = legend.get_frame_on()

        box = legend.get_frame()
        props['background_color'] = convert_color_to_hex(box.get_facecolor())
        props['edge_color'] = convert_color_to_hex(box.get_edgecolor())
        props['transparency'] = box.get_alpha()

        text = legend.get_texts()[0]
        props['entries_font'] = text.get_fontname()
        props['entries_size'] = text.get_fontsize()
        props['entries_color'] = convert_color_to_hex(text.get_color())

        props['marker_size'] = legend.handlelength
        props['shadow'] = legend.shadow

        boxstyle = legend.legendPatch.get_boxstyle()
        if isinstance(boxstyle, BoxStyle.Round):
            props['round_edges'] = True
        else:
            props['round_edges'] = False

        props['columns'] = legend._ncol
        props['column_spacing'] = legend.columnspacing
        props['label_spacing'] = legend.labelspacing

        position = legend._legend_handle_box.get_children()[0].align
        if position == "baseline":
            props['marker_position'] = "Left of Entries"
        else:
            props['marker_position'] = "Right of Entries"

        props['markers'] = legend.numpoints
        props['border_padding'] = legend.borderpad
        props['marker_label_padding'] = legend.handletextpad

        return cls(props)
Beispiel #2
0
 def test_apply_properties_on_figure_with_curve_sets_errorbar_color(self):
     cap_color = self.new_curve[1][0].get_color()
     bar_color = self.new_curve[2][0].get_color()
     if cap_color[0] != '#':
         cap_color = convert_color_to_hex(cap_color[0])
     if bar_color[0] != '#':
         bar_color = convert_color_to_hex(bar_color[0])
     self.assertEqual(new_curve_view_props['ecolor'], cap_color)
     self.assertEqual(new_curve_view_props['ecolor'], bar_color)
Beispiel #3
0
 def test_apply_properties_on_figure_with_legend_sets_edge_color(self):
     if int(matplotlib.__version__[0]) >= 2:
         self.assertEqual(
             new_legend_props['edge_color'],
             convert_color_to_hex(
                 self.new_legend.get_frame().get_edgecolor()))
     else:
         self.assertEqual(
             "#000000",
             convert_color_to_hex(
                 self.new_legend.get_frame().get_edgecolor()))
Beispiel #4
0
 def _get_line_props_from_curve(curve, props):
     """Get a curve's line properties and add to props dict"""
     if not curve:
         props['linestyle'] = 'None'
         props['drawstyle'] = 'default'
         props['linewidth'] = rcParams['lines.linewidth']
         props['color'] = convert_color_to_hex(rcParams['lines.color'])
     else:
         props['linestyle'] = LINESTYLE_MAP[curve.get_linestyle()]
         props['drawstyle'] = curve.get_drawstyle()
         props['linewidth'] = curve.get_linewidth()
         props['color'] = convert_color_to_hex(curve.get_color())
     return props
Beispiel #5
0
 def _get_errorbars_props_from_curve(curve, props):
     """Get a curve's errorbar properties and add to props dict"""
     props['hide_errors'] = getattr(curve, 'hide_errors',
                                    errorbars_hidden(curve))
     # ErrorbarContainer does not have 'errorevery' as an attribute directly
     # So to get this property take from errorbar lines curve
     try:
         barlines = curve[2][0]
         props['errorevery'] = int(
             barlines.axes.creation_args[len(barlines.axes.creation_args) -
                                         1]['errorevery'])
     except (IndexError, TypeError, KeyError):
         props['errorevery'] = 1
     try:
         caps = curve[1]
         props['capsize'] = float(caps[0].get_markersize() / 2)
         props['capthick'] = float(caps[0].get_markeredgewidth())
     except (IndexError, TypeError):
         props['capsize'] = 0.0
         props['capthick'] = 1.0
     try:
         bars = curve[2]
         props['elinewidth'] = float(bars[0].get_linewidth()[0])
         props['ecolor'] = convert_color_to_hex(bars[0].get_color()[0])
     except (IndexError, TypeError):
         props['elinewidth'] = 1.0
         # if the errorbars don't have a default color, use the line's color
         props['ecolor'] = curve.get_color()
     return props
Beispiel #6
0
def waterfall_update_fill(ax):
    # Get the colours of each fill so they can be reapplied after updating.
    colours = []
    for collection in ax.collections:
        if isinstance(collection, PolyCollection):
            colours.append(collection.get_facecolor())

    waterfall_remove_fill(ax)
    waterfall_create_fill(ax)

    poly_collections = get_waterfall_fills(ax)
    line_colours = True
    # If there are more fill areas than colours, this means that new curves have been added to the plot
    # (overplotting). In which case, we need to determine whether the fill colours are set to match the line
    # colours by checking that the colour of each fill that existed previously is the same as the line it belongs
    # to. If so, the list of colours is appended to with the colours of the new lines. Otherwise the fills are
    # all set to the same colour and so the list of colours is extended with the same colour for each new curve.
    if len(poly_collections) > len(colours):
        for i in range(len(colours) - 1):
            if convert_color_to_hex(colours[i][0]) != ax.get_lines()[i].get_color():
                line_colours = False
                break

        colours_length = len(colours)
        if line_colours:
            for i in range(colours_length, len(poly_collections)):
                colours.append(ax.get_lines()[i].get_color())
        else:
            for i in range(colours_length, len(poly_collections)):
                colours.append(colours[0])

    for i, collection in enumerate(poly_collections):
        collection.set_color(colours[i])
Beispiel #7
0
 def _get_marker_props_from_curve(curve, props):
     """Get a curve's marker properties and add to props dict"""
     if not curve:
         props['marker'] = 'None'
         props['markersize'] = rcParams['lines.markersize']
         props['markerfacecolor'] = convert_color_to_hex(
             rcParams['lines.color'])
         props['markeredgecolor'] = convert_color_to_hex(
             rcParams['lines.color'])
     else:
         props['marker'] = get_marker_name(curve.get_marker())
         props['markersize'] = curve.get_markersize()
         props['markerfacecolor'] = convert_color_to_hex(
             curve.get_markerfacecolor())
         props['markeredgecolor'] = convert_color_to_hex(
             curve.get_markeredgecolor())
     return props
Beispiel #8
0
def waterfall_fill_is_line_colour(ax):
    i = 0
    # Check that for each line, the fill area is the same colour as the line.
    for collection in ax.collections:
        if isinstance(collection, PolyCollection):
            line_colour = ax.get_lines()[i].get_color()
            poly_colour = convert_color_to_hex(collection.get_facecolor()[0])
            if line_colour != poly_colour:
                return False
            i += 1
    return True
Beispiel #9
0
def get_subplots_command_kwargs(fig):
    ax = fig.get_axes()[0]
    kwargs = {
        'dpi': fig.dpi,
        'edgecolor': convert_color_to_hex(fig.get_edgecolor()),
        'facecolor': convert_color_to_hex(fig.get_facecolor()),
        'figsize': [fig.get_figwidth(),
                    fig.get_figheight()],
        'frameon': fig.frameon,
        'num': fig.get_label(),
        'subplot_kw': {
            'projection': 'mantid'
        },
    }
    if LooseVersion('3.1.3') < LooseVersion(matplotlib.__version__):
        kwargs['ncols'] = ax.get_gridspec().ncols
        kwargs['nrows'] = ax.get_gridspec().nrows
    else:
        kwargs['ncols'] = ax.numCols
        kwargs['nrows'] = ax.numRows
    return kwargs
Beispiel #10
0
    def init_view(self):
        # This function sets the correct values in the menu when it is first opened.

        if self.ax.waterfall_has_fill():
            self.view.enable_fill_group_box.setChecked(True)

            if datafunctions.waterfall_fill_is_line_colour(self.ax):
                self.view.use_line_colour_radio_button.setChecked(True)
            else:
                self.view.use_solid_colour_radio_button.setChecked(True)
                poly = next(poly_collection for poly_collection in self.ax.collections
                            if isinstance(poly_collection, PolyCollection))
                self.view.colour_selector_widget.set_color(convert_color_to_hex(poly.get_facecolor().tolist()[0]))
Beispiel #11
0
    def test_toggle_normalisation_on_contour_plot_maintains_contour_line_colour(
            self):
        from mantid.plots.utility import convert_color_to_hex
        ws = CreateWorkspace(DataX=[1, 2, 3, 4, 2, 4, 6, 8],
                             DataY=[2] * 8,
                             NSpec=2,
                             OutputWorkspace="test_ws")
        fig = plot_contour([ws])

        for col in fig.get_axes()[0].collections:
            col.set_color("#ff9900")

        mock_canvas = MagicMock(figure=fig)
        fig_manager_mock = MagicMock(canvas=mock_canvas)
        fig_interactor = FigureInteraction(fig_manager_mock)
        fig_interactor._toggle_normalization(fig.axes[0])

        self.assertTrue(
            all(
                convert_color_to_hex(col.get_edgecolor()[0]) == "#ff9900"
                for col in fig.get_axes()[0].collections))
    def test_changing_line_colour_on_a_waterfall_plot_with_filled_areas_changes_fill_colour_to_match(self):
        fig = self.make_figure_with_multiple_curves()

        mock_view = Mock(get_selected_ax_name=lambda: "Axes 0: (0, 0)",
                         get_current_curve_name=lambda: "Workspace")

        ax = fig.get_axes()[0]
        ax.lines[0].set_color('#ff9900')
        ax.lines[1].set_color('#008fff')
        ax.lines[2].set_color('#42ff00')

        # Create waterfall plot and add filled areas.
        ax.set_waterfall(True)
        ax.set_waterfall_fill(True)

        presenter = self._generate_presenter(fig=fig, mock_view=mock_view)
        # Change the colour of one of the lines.
        new_plot_kwargs = {'color': '#ffff00'}
        presenter._replot_current_curve(new_plot_kwargs)

        # The fill for that line should be the new colour.
        self.assertEqual(convert_color_to_hex(ax.collections[0].get_facecolor()[0]), ax.lines[0].get_color())
Beispiel #13
0
    def test_overplotting_onto_waterfall_plot_with_line_colour_fills_adds_another_filled_area_with_new_line_colour(
            self):
        fig, ax = plt.subplots(subplot_kw={'projection': 'mantid'})
        ax.plot([0, 1], [0, 1], color="#ff9900")
        ax.plot([0, 1], [0, 1], color="#00d1ff")

        # Make a waterfall plot.
        ax.set_waterfall(True)
        # Add filled areas.
        ax.set_waterfall_fill(True)
        # Set the fills to be the same colour as their lines.
        ax.collections[0].set_facecolor(ax.lines[0].get_color())
        ax.collections[1].set_facecolor(ax.lines[0].get_color())

        # Plot another line and make it join the waterfall.
        ax.plot([0, 1], [0, 1], color='#00fff0')
        datafunctions.convert_single_line_to_waterfall(ax, 2)
        datafunctions.waterfall_update_fill(ax)

        # Check that there are now three filled areas and the new line colour matches the new fill colour.
        self.assertEqual(
            convert_color_to_hex(ax.collections[2].get_facecolor()[0]),
            ax.lines[2].get_color())
Beispiel #14
0
    def set_up_color_selector_toolbar_button(self, fig):
        # check if the action is already in the toolbar
        if self._actions.get('line_colour'):
            return

        a = self.addAction(get_icon('mdi.palette'), "Line Colour",
                           lambda: None)
        self._actions['line_colour'] = a

        if figure_type(fig) == FigureType.Wireframe:
            a.setToolTip("Set the colour of the wireframe.")
        else:
            a.setToolTip("Set the colour of the contour lines.")

        line_collection = next(col for col in fig.get_axes()[0].collections
                               if isinstance(col, LineCollection))
        initial_colour = convert_color_to_hex(line_collection.get_color()[0])

        colour_dialog = QtWidgets.QColorDialog(QtGui.QColor(initial_colour))
        colour_dialog.setOption(QtWidgets.QColorDialog.NoButtons)
        colour_dialog.setOption(QtWidgets.QColorDialog.DontUseNativeDialog)
        colour_dialog.currentColorChanged.connect(
            self.change_line_collection_colour)

        button = [
            child for child in self.children()
            if isinstance(child, QtWidgets.QToolButton)
        ][-1]

        menu = QtWidgets.QMenu("Menu", parent=button)
        colour_selector_action = QtWidgets.QWidgetAction(menu)
        colour_selector_action.setDefaultWidget(colour_dialog)
        menu.addAction(colour_selector_action)

        button.setMenu(menu)
        button.setPopupMode(QtWidgets.QToolButton.InstantPopup)
Beispiel #15
0
#
# Copyright &copy; 2019 ISIS Rutherford Appleton Laboratory UKRI,
#   NScD Oak Ridge National Laboratory, European Spallation Source,
#   Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
#  This file is part of the mantid workbench.

from mantid.plots.utility import convert_color_to_hex
from matplotlib import rcParams
from qtpy.QtCore import QRegExp
from qtpy.QtGui import QColor, QRegExpValidator
from qtpy.QtWidgets import (QWidget, QLineEdit, QPushButton, QHBoxLayout,
                            QColorDialog)


MPL_DEFAULT = convert_color_to_hex(rcParams['lines.color'])


class ColorSelector(QWidget):

    def __init__(self, initial_color=MPL_DEFAULT, parent=None):
        super(ColorSelector, self).__init__(parent=parent)

        self.initial_color = QColor(initial_color)

        # Create line edit and push button and add to a horizontal layout
        self.line_edit = QLineEdit(self)
        self.button = QPushButton(self)
        self.h_layout = QHBoxLayout(self)
        self.h_layout.addWidget(self.line_edit)
        self.h_layout.addWidget(self.button)
Beispiel #16
0
def generate_axis_facecolor_commands(ax):
    # Check that the colour is different to default, otherwise return None.
    colour = convert_color_to_hex(ax.get_facecolor()).lower()
    if colour != convert_color_to_hex(DEFAULT_FACECOLOR).lower():
        return BASE_SET_FACECOLOR_COMMAND.format(colour)
    return None
Beispiel #17
0
# SPDX - License - Identifier: GPL - 3.0 +
#  This file is part of the mantid workbench.
from distutils.version import LooseVersion

import matplotlib
from matplotlib import rcParams
from numpy import isclose

from mantid.plots.utility import convert_color_to_hex
from workbench.plotting.plotscriptgenerator.utils import convert_args_to_string

BASE_SUBPLOTS_COMMAND = "plt.subplots({})"

default_kwargs = {
    'dpi': rcParams['figure.dpi'],
    'edgecolor': convert_color_to_hex(rcParams['figure.edgecolor']),
    'facecolor': convert_color_to_hex(rcParams['figure.facecolor']),
    'figsize': rcParams['figure.figsize'],
    'frameon': rcParams['figure.frameon'],
    'ncols': 1,
    'nrows': 1,
    'num': ''
}


def get_subplots_command_kwargs(fig):
    ax = fig.get_axes()[0]
    kwargs = {
        'dpi': fig.dpi,
        'edgecolor': convert_color_to_hex(fig.get_edgecolor()),
        'facecolor': convert_color_to_hex(fig.get_facecolor()),
Beispiel #18
0
#   NScD Oak Ridge National Laboratory, European Spallation Source,
#   Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
#  This file is part of the mantid workbench.

from matplotlib import rcParams
from matplotlib.font_manager import FontProperties
from mantid.plots.legend import LegendProperties
from mantid.plots.utility import convert_color_to_hex
from workbench.plotting.plotscriptgenerator.utils import convert_args_to_string

# Default values of all options that are accessible via the legend tab in the plot settings.
mpl_default_kwargs = {
    'visible': True,
    'title': '',
    'background_color': convert_color_to_hex(
        rcParams['axes.facecolor']),  # inherits from axes by default
    'edge_color': convert_color_to_hex(rcParams['legend.edgecolor']),
    'transparency': rcParams['legend.framealpha'],
    'entries_font': 'DejaVu Sans',
    'entries_size': rcParams['legend.fontsize'],
    'entries_color': '#000000',
    'title_font': 'DejaVu Sans',
    'title_size': rcParams['axes.labelsize'],  # Uses axes size by default
    'title_color': '#000000',
    'marker_size': rcParams['legend.handlelength'],
    'box_visible': rcParams['legend.frameon'],
    'shadow': rcParams['legend.shadow'],
    'round_edges': rcParams['legend.fancybox'],
    'columns': 1,
    'column_spacing': rcParams['legend.columnspacing'],
    'label_spacing': rcParams['legend.labelspacing'],
Beispiel #19
0
 def set_color(self, color_hex):
     self.line_edit.setText(convert_color_to_hex(color_hex))