Exemplo n.º 1
0
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):

    x, y, z = xyz
    if zdir == "y":
        xy1, z1 = (x, z), y
    elif zdir == "y":
        xy1, z1 = (y, z), x
    else:
        xy1, z1 = (x, y), z

    text_path = TextPath((0, 0), s, size=size, usetex=usetex)
    trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])

    p1 = PathPatch(trans.transform_path(text_path), **kwargs)
    ax.add_patch(p1)
    art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
Exemplo n.º 2
0
def letterAt(letter, x, y, yscale=1, ax=None, color=None, alpha=1.0):

    #fp = FontProperties(family="Arial", weight="bold")
    fp = FontProperties(family="Ubuntu", weight="bold")
    globscale = 1.35
    LETTERS = {
        "T": TextPath((-0.305, 0), "T", size=1, prop=fp),
        "G": TextPath((-0.384, 0), "G", size=1, prop=fp),
        "A": TextPath((-0.35, 0), "A", size=1, prop=fp),
        "C": TextPath((-0.366, 0), "C", size=1, prop=fp),
        "UP": TextPath((-0.488, 0), '$\\Uparrow$', size=1, prop=fp),
        "DN": TextPath((-0.488, 0), '$\\Downarrow$', size=1, prop=fp),
        "(": TextPath((-0.25, 0), "(", size=1, prop=fp),
        ".": TextPath((-0.125, 0), "-", size=1, prop=fp),
        ")": TextPath((-0.1, 0), ")", size=1, prop=fp)
    }
    COLOR_SCHEME = {
        'G': 'orange',
        'A': 'red',
        'C': 'blue',
        'T': 'darkgreen',
        'UP': 'green',
        'DN': 'red',
        '(': 'black',
        '.': 'black',
        ')': 'black'
    }

    text = LETTERS[letter]

    chosen_color = COLOR_SCHEME[letter]
    if color is not None:
        chosen_color = color

    t = mpl.transforms.Affine2D().scale(1*globscale, yscale*globscale) + \
        mpl.transforms.Affine2D().translate(x,y) + ax.transData
    p = PathPatch(text, lw=0, fc=chosen_color, alpha=alpha, transform=t)
    if ax != None:
        ax.add_artist(p)
    return p
Exemplo n.º 3
0
    def display_points(self, image_idx, image):
        visible_points_coords = self.database.get_visible_points_coords(image)
        self.clear_images(image_idx)

        for point_id, coords in visible_points_coords.items():
            color = distinct_colors[divmod(hash(point_id), 19)[1]]
            text_path = TextPath((0, 0), point_id, size=10)
            p1 = PathPatch(text_path, transform=IdentityTransform(), alpha=1, color=color)
            offsetbox2 = AuxTransformBox(IdentityTransform())
            offsetbox2.add_artist(p1)
            ab = AnnotationBbox(offsetbox2, ((coords[0] + 30), (coords[1] + 30)), bboxprops=dict(alpha=0.05))
            circle = mpatches.Circle((coords[0], coords[1]), 20, color=color, fill=False)

            self.plt_artists[image_idx].append(ab)
            self.plt_artists[image_idx].append(circle)

            self.subplots[image_idx].add_artist(ab)
            self.subplots[image_idx].add_artist(circle)
        self.figures[image_idx].canvas.draw_idle()
Exemplo n.º 4
0
def text3d(ax,
           xyz,
           s,
           zdir="z",
           size=0.1,
           angle=0,
           font='Arial',
           weight='normal',
           ha='left',
           va='center',
           **kwargs):
    x, y, z = xyz
    xlim, ylim, zlim = ax.get_xlim(), ax.get_ylim(), ax.get_zlim()
    xmin, xmax, ymin, ymax, zmin, zmax = xlim[0], xlim[1], ylim[0], ylim[
        1], zlim[0], zlim[1]
    xlen, ylen, zlen = xmax - xmin, ymax - ymin, zmax - zmin
    minLen_axis = np.min([xlen, ylen, zlen])
    aspect = ax.get_box_aspect()
    fontscale = 1
    if zdir == "y":
        xy, z, fontscale = (x, z), y, (xlen / zlen) / (aspect[0] / aspect[2])
    elif zdir == "x":
        xy, z, fontscale = (y, z), x, (ylen / zlen) / (aspect[1] / aspect[2])
    else:
        xy, z, fontscale = (x, y), z, (xlen / ylen) / (aspect[0] / aspect[1])
    path = TextPath((0, 0),
                    s,
                    size=size,
                    prop=FontProperties(family=font, weight=weight))
    V = path.vertices
    if (ha == 'center'):
        V[:, 0] -= (V[:, 0].max() - V[:, 0].min()) / 2  # 居中
    elif (ha == 'right'):
        V[:, 0] -= V[:, 0].max()
    if (va == 'center'):
        V[:, 1] -= (V[:, 1].max() - V[:, 1].min()) / 2  # 居中
    elif (va == 'top'):
        V[:, 1] -= V[:, 1].max()
    trans = Affine2D().rotate(angle / 180 * np.pi).scale(
        1, 1 / fontscale).translate(xy[0], xy[1])
    path = PathPatch(trans.transform_path(path), clip_on=False, **kwargs)
    ax.add_patch(path)
    art3d.pathpatch_2d_to_3d(path, z=z, zdir=zdir)
Exemplo n.º 5
0
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
    '''
    Plots the string 's' on the axes 'ax', with position 'xyz', size 'size',
    and rotation angle 'angle'.  'zdir' gives the axis which is to be treated
    as the third dimension.  usetex is a boolean indicating whether the string
    should be interpreted as latex or not.  Any additional keyword arguments
    are passed on to transform_path.

    Note: zdir affects the interpretation of xyz.
    '''
    x, y, z = xyz
    if zdir == "y":
        xy1, z1 = (x, z), y
    elif zdir == "y":
        xy1, z1 = (y, z), x
    else:
        xy1, z1 = (x, y), z

    text_path = TextPath((0, 0), s, size=size, usetex=usetex)
    trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])

    p1 = PathPatch(trans.transform_path(text_path), **kwargs)
    ax.add_patch(p1)
    art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
Exemplo n.º 6
0
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
    """
    Plots the string *s* on the axes *ax*, with position *xyz*, size *size*,
    and rotation angle *angle*. *zdir* gives the axis which is to be treated as
    the third dimension. *usetex* is a boolean indicating whether the string
    should be run through a LaTeX subprocess or not.  Any additional keyword
    arguments are forwarded to `.transform_path`.

    Note: zdir affects the interpretation of xyz.
    """
    x, y, z = xyz
    if zdir == "y":
        xy1, z1 = (x, z), y
    elif zdir == "x":
        xy1, z1 = (y, z), x
    else:
        xy1, z1 = (x, y), z

    text_path = TextPath((0, 0), s, size=size, usetex=usetex)
    trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])

    p1 = PathPatch(trans.transform_path(text_path), **kwargs)
    ax.add_patch(p1)
    art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
Exemplo n.º 7
0
        order_colors_pos = c_pos[np.argsort(matrix[site][c_pos])]
        order_colors_neg = c_neg[np.argsort(-matrix[site][c_neg])]
        for c in order_colors_pos:
            liste.append( (list_aa[c],matrix[site,c],'+') )
        for c in order_colors_neg:
            liste.append( (list_aa[c],-matrix[site,c],'-') )
        all_scores.append(liste)
    maxi_size = np.abs(matrix).sum(-1).max()
    return all_scores,maxi_size



fp = FontProperties(family="Arial", weight="bold")
globscale = 1.35
list_aa = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V',  'W','Y','$\\boxminus$']
LETTERS = dict([ (letter, TextPath((-0.30, 0), letter, size=1, prop=fp) )   for letter in list_aa] )
COLOR_SCHEME = dict( [(letter,aa_color(letter)) for letter in list_aa] )

def Sequence_logo(matrix, ax = None,data_type=None,figsize=None,ylabel = None,title=None,epsilon=1e-4,show=True,
                  nrows=1,ticks_every=1,ticks_labels_size=14,title_size=20, x_start =0,x_stop=None):
    if data_type is None:
        if matrix.min()>=0:
            data_type='mean'
        else:
            data_type = 'weights'

    if ax is not None:
        show = False
        return_fig = False
    else:
        if figsize is None:
Exemplo n.º 8
0
import matplotlib as mpl
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from matplotlib.font_manager import FontProperties

fp = FontProperties(family="Arial", weight="bold")
globscale = 1.35
NUMBERS = {
    "3": TextPath((-0.305, 0), "3", size=1, prop=fp),
    "5": TextPath((-0.35, 0), "5", size=1, prop=fp),
    "7": TextPath((-0.366, 0), "7", size=1, prop=fp),
    "9": TextPath((-0.384, 0), "9", size=1, prop=fp),
    "11": TextPath((-0.398, 0), "E", size=1, prop=fp)
}

ALPHABETS = {
    "A": TextPath((-0.305, 0), "A", size=1, prop=fp),
    "T": TextPath((-0.35, 0), "T", size=1, prop=fp),
    "G": TextPath((-0.366, 0), "G", size=1, prop=fp),
    "C": TextPath((-0.384, 0), "C", size=1, prop=fp)
}

COLOR_SCHEME = {
    '3': 'orange',
    '5': 'red',
    '7': 'blue',
    '9': 'navy',
    '11': 'darkgreen'
}

COLOR_SCHEME_ALPHABET = {'A': 'orange', 'T': 'red', 'G': 'blue', 'C': 'navy'}
Exemplo n.º 9
0
    def __init__(self,
                 transform,
                 label_x,
                 label_y,
                 length=0.15,
                 fontsize=0.08,
                 loc=2,
                 angle=0,
                 aspect_ratio=1,
                 pad=0.4,
                 borderpad=0.4,
                 frameon=False,
                 color='w',
                 alpha=1,
                 sep_x=0.01,
                 sep_y=0,
                 fontproperties=None,
                 back_length=0.15,
                 head_width=10,
                 head_length=15,
                 tail_width=2,
                 text_props=None,
                 arrow_props=None,
                 **kwargs):
        """
        Draw two perpendicular arrows to indicate directions.

        Parameters
        ----------
        transform : `matplotlib.transforms.Transform`
            The transformation object for the coordinate system in use, i.e.,
            :attr:`matplotlib.axes.Axes.transAxes`.

        label_x, label_y : str
            Label text for the x and y arrows

        length : float, optional, default: 0.15
            Length of the arrow, given in coordinates of *transform*.

        fontsize : float, optional, default: 0.08
            Size of label strings, given in coordinates of *transform*.

        loc : int, optional, default: 2
            Location of the direction arrows. Valid location codes are::

                'upper right'  : 1,
                'upper left'   : 2,
                'lower left'   : 3,
                'lower right'  : 4,
                'right'        : 5,
                'center left'  : 6,
                'center right' : 7,
                'lower center' : 8,
                'upper center' : 9,
                'center'       : 10

        angle : float, optional, default: 0
            The angle of the arrows in degrees.

        aspect_ratio : float, optional, default: 1
            The ratio of the length of arrow_x and arrow_y.
            Negative numbers can be used to change the direction.

        pad : float, optional, default: 0.4
            Padding around the labels and arrows, in fraction of the font size.

        borderpad : float, optional, default: 0.4
            Border padding, in fraction of the font size.

        frameon : bool, optional, default: False
            If True, draw a box around the arrows and labels.

        color : str, optional, default: 'white'
            Color for the arrows and labels.

        alpha : float, optional, default: 1
            Alpha values of the arrows and labels

        sep_x, sep_y : float, optional, default: 0.01 and 0 respectively
            Separation between the arrows and labels in coordinates of
            *transform*.

        fontproperties : `matplotlib.font_manager.FontProperties`, optional
            Font properties for the label text.

        back_length : float, optional, default: 0.15
            Fraction of the arrow behind the arrow crossing.

        head_width : float, optional, default: 10
            Width of arrow head, sent to ArrowStyle.

        head_length : float, optional, default: 15
            Length of arrow head, sent to ArrowStyle.

        tail_width : float, optional, default: 2
            Width of arrow tail, sent to ArrowStyle.

        text_props, arrow_props : dict
            Properties of the text and arrows, passed to
            `.textpath.TextPath` and `.patches.FancyArrowPatch`.

        **kwargs
            Keyworded arguments to pass to
            :class:`matplotlib.offsetbox.AnchoredOffsetbox`.

        Attributes
        ----------
        arrow_x, arrow_y : `matplotlib.patches.FancyArrowPatch`
            Arrow x and y

        text_path_x, text_path_y : `matplotlib.textpath.TextPath`
            Path for arrow labels

        p_x, p_y : `matplotlib.patches.PathPatch`
            Patch for arrow labels

        box : `matplotlib.offsetbox.AuxTransformBox`
            Container for the arrows and labels.

        Notes
        -----
        If *prop* is passed as a keyword argument, but *fontproperties* is
        not, then *prop* is be assumed to be the intended *fontproperties*.
        Using both *prop* and *fontproperties* is not supported.

        Examples
        --------
        >>> import matplotlib.pyplot as plt
        >>> import numpy as np
        >>> from mpl_toolkits.axes_grid1.anchored_artists import (
        ...     AnchoredDirectionArrows)
        >>> fig, ax = plt.subplots()
        >>> ax.imshow(np.random.random((10, 10)))
        >>> arrows = AnchoredDirectionArrows(ax.transAxes, '111', '110')
        >>> ax.add_artist(arrows)
        >>> fig.show()

        Using several of the optional parameters, creating downward pointing
        arrow and high contrast text labels.

        >>> import matplotlib.font_manager as fm
        >>> fontprops = fm.FontProperties(family='monospace')
        >>> arrows = AnchoredDirectionArrows(ax.transAxes, 'East', 'South',
        ...                                  loc='lower left', color='k',
        ...                                  aspect_ratio=-1, sep_x=0.02,
        ...                                  sep_y=-0.01,
        ...                                  text_props={'ec':'w', 'fc':'k'},
        ...                                  fontproperties=fontprops)
        """
        if arrow_props is None:
            arrow_props = {}

        if text_props is None:
            text_props = {}

        arrowstyle = ArrowStyle("Simple",
                                head_width=head_width,
                                head_length=head_length,
                                tail_width=tail_width)

        if fontproperties is None and 'prop' in kwargs:
            fontproperties = kwargs.pop('prop')

        if 'color' not in arrow_props:
            arrow_props['color'] = color

        if 'alpha' not in arrow_props:
            arrow_props['alpha'] = alpha

        if 'color' not in text_props:
            text_props['color'] = color

        if 'alpha' not in text_props:
            text_props['alpha'] = alpha

        t_start = transform
        t_end = t_start + transforms.Affine2D().rotate_deg(angle)

        self.box = AuxTransformBox(t_end)

        length_x = length
        length_y = length * aspect_ratio

        self.arrow_x = FancyArrowPatch((0, back_length * length_y),
                                       (length_x, back_length * length_y),
                                       arrowstyle=arrowstyle,
                                       shrinkA=0.0,
                                       shrinkB=0.0,
                                       **arrow_props)

        self.arrow_y = FancyArrowPatch((back_length * length_x, 0),
                                       (back_length * length_x, length_y),
                                       arrowstyle=arrowstyle,
                                       shrinkA=0.0,
                                       shrinkB=0.0,
                                       **arrow_props)

        self.box.add_artist(self.arrow_x)
        self.box.add_artist(self.arrow_y)

        text_path_x = TextPath(
            (length_x + sep_x, back_length * length_y + sep_y),
            label_x,
            size=fontsize,
            prop=fontproperties)
        self.p_x = PathPatch(text_path_x, transform=t_start, **text_props)
        self.box.add_artist(self.p_x)

        text_path_y = TextPath((length_x * back_length + sep_x, length_y *
                                (1 - back_length) + sep_y),
                               label_y,
                               size=fontsize,
                               prop=fontproperties)
        self.p_y = PathPatch(text_path_y, **text_props)
        self.box.add_artist(self.p_y)

        AnchoredOffsetbox.__init__(self,
                                   loc,
                                   pad=pad,
                                   borderpad=borderpad,
                                   child=self.box,
                                   frameon=frameon,
                                   **kwargs)
Exemplo n.º 10
0
                'M':(-0.301,0), 
                'N':(-0.301,0), 
                'P':(-0.301,0), 
                'Q':(-0.301,0), 
                'R':(-0.301,0), 
                'S':(-0.301,0), 
                'T':(-0.301,0), 
                'V':(-0.301,0), 
                'W':(-0.301,0), 
                'Y':(-0.301,0), 
                'X':(-0.301,0)
                }

fp = FontProperties(family="Ubuntu", weight="bold") 

LETTERS = {i: TextPath((aa_textpaths[i]), i, size=1, prop=fp) for i in aa_letters}

globscale = 1.35


# define color schemes
aa_1 = {i:'blue' for i in ['R','H','K']}
aa_2 = {i:'red' for i in ['D','E']}
aa_3 = {i:'cyan' for i in ['S','T','N','Q']}
aa_4 = {i:'green' for i in ['A','I','L','M','F','W','Y','V']}
aa_5 = {i:'yellow' for i in ['C','G','P']}

COLOR_SCHEME = {**aa_1,**aa_2,**aa_3,**aa_4,**aa_5}

def letterAt(letter, x, y, yscale=1, ax=None):
    text = LETTERS[letter]
Exemplo n.º 11
0
# visualize the data
x = data.food
y = data.sleep
groups = data.groupby('label')
colors = ['crimson', 'mediumblue']

#plot
#src https://stackoverflow.com/questions/21654635/scatter-plots-in-pandas-pyplot-how-to-plot-by-category
#plt.figure(figsize=[8,8])
i = 0
fig, ax = plt.subplots()
for name, group in groups:
    letter = group.isCat.unique()
    letter = letter[0]
    ax.scatter(group.food, group.sleep, c=colors[i],  marker=TextPath((0, 0), letter), s = 400, alpha =.8, label = name)
    i+=1
##ax.legend()
plt.title("Cat?")
plt.xlabel("Food (in grams)")
plt.ylabel("Sleep (in hours)")
plt.show()


### Step 2. Train
X = data[['food','sleep']]
y = data['label']
#x_train, Y_train =
sample = [[600,22.0]]

# 2a. SVM Model
Exemplo n.º 12
0
                         (args.predictionfolder, args.pdbid))
]
#AvailableGridPrediction = [i for i in glob.glob("%s/*_result_reformat.pickle" %(args.predictionfolder))]

# ============================
# Configure Matplotlib
# ============================
import matplotlib as mpl
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from matplotlib.font_manager import FontProperties

fp = FontProperties(family="sans-serif", weight="bold")
globscale = 1.35
LETTERS = {
    "U": TextPath((-0.365, 0), "U", size=1, prop=fp),
    "G": TextPath((-0.384, 0), "G", size=1, prop=fp),
    "A": TextPath((-0.35, 0), "A", size=1, prop=fp),
    "C": TextPath((-0.325, 0), "C", size=1, prop=fp)
}
# RNAC color scheme
COLOR_SCHEME = {'G': '#FFAF00', 'A': '#06C806', 'C': '#0003C6', 'U': '#C90101'}

# Our NucleicNet Color scheme
#COLOR_SCHEME = {'G': '#AEF3EB',
#                'A': '#5B9AE8',
#                'C': '#E30F38',
#                'U': '#F1BBC1'}


def letterAt(letter, x, y, yscale=1, ax=None):
Exemplo n.º 13
0
def logo_plot_in_axis(df,
                      seqID,
                      ax,
                      refseq=True,
                      key_residues=None,
                      refplot=False,
                      colors="WEBLOGO",
                      **kwargs):
    """Generates classic **LOGO** plot in a given axis.

    :param df: Data container.
    :type df: Union[:class:`.DesignFrame`, :class:`.SequenceFrame`]
    :param str seqID: |seqID_param|.
    :param bool refseq: if :data:`True` (default), mark the original residues according to
        the reference sequence.
    :param key_residues: |keyres_param|.
    :type key_residues: |keyres_param|
    :param bool refplot: When :data:`True`, it will reorder the residues in each position
        so that the reference residue will be on the bottom and setting a two-color scheme
        (provide a single color name in ``colors``) that allows to quickly identify the reference
        type in each position.
    :param colors: Colors to assign; it can be the name of a available color set or
        a dictionary with a color for each type. Available color schemes are: Weblogo
        (default), Hydrophobicity, Chemistry, and Charge.
    :type colors: Union[:class:`str`, :class:`dict`]

    :return: :class:`~matplotlib.axes.Axes` - secondary axis

    .. seealso::
        :func:`.logo_plot`
    """

    order = [
        "A", "V", "I", "L", "M", "F", "Y", "W", "S", "T", "N", "Q", "R", "H",
        "K", "D", "E", "C", "G", "P"
    ]
    data = copy.deepcopy(df)
    if data.empty:
        raise ValueError("Provided data container is empty. Nothing to plot.")

    mpl.rcParams['svg.fonttype'] = 'none'
    # Graphical Properties of resizable letters
    path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                        '../components/square.ttf')
    fp = FontProperties(fname=path, weight="bold")
    globscale = 1.22
    letters_shift = -0.5
    LETTERS = {}
    if isinstance(colors, dict):
        for aa in colors:
            LETTERS[aa] = TextPath((letters_shift, 0), aa, size=1, prop=fp)
    elif isinstance(colors, str):
        for aa in color_scheme(colors):
            LETTERS[aa] = TextPath((letters_shift, 0), aa, size=1, prop=fp)
    else:
        raise ValueError(
            "Colors need to either be a string representing the name of a available "
            "color set or a dictionary with a color for each type.")

    # Data type management.
    if not isinstance(data, pd.DataFrame):
        raise ValueError(
            "Input data must be in a DataFrame, DesignFrame or SequenceFrame")
    else:
        if not isinstance(data, (DesignFrame, SequenceFrame)):
            if len(set(data.columns.values).intersection(
                    set(order))) == len(order):
                data = SequenceFrame(data)
            else:
                data = DesignFrame(data)
    if isinstance(data, DesignFrame):
        data = data.sequence_frequencies(seqID)

    # Refseq and key_residues management.
    ref_seq = data.get_reference_sequence(seqID,
                                          key_residues) if refseq else ""
    # data and key_residues management.
    _data = data.get_key_residues(key_residues)

    maxv = int(math.ceil(data.max_hight()))

    ticks = len(_data)
    # This is applied if it comes from the logo_plot function
    if 'line_break' in kwargs and kwargs['line_break'] is not None:
        if ticks < kwargs['line_break']:
            ticks = kwargs['line_break']
    ax.set_xticks(np.arange(0.5, ticks + 1))
    ax.set_yticks(range(0, maxv + 1))
    ax.set_xticklabels(_data.index.values)
    ax.set_yticklabels(np.arange(0, maxv + 1, 1))
    ax.set_xlim(-0.1, ticks + 0.1)
    ax2 = None
    if ref_seq is not None:
        ax2 = ax.twiny()
        ax2.set_xticks(ax.get_xticks())
        ax2.set_xticklabels(list(ref_seq))
        ax2.set_xlim(-0.1, ticks + 0.1)
    sns.despine(ax=ax, trim=True)
    ax.grid(False)
    if ref_seq is not None:
        sns.despine(ax=ax2, top=False, right=True, left=True, trim=True)
        ax2.grid(False)
    ax.lines = []
    wdata = _dataframe2logo(_data)
    x = 0.5
    maxi = 0
    for scores in wdata:
        y = 0
        for base, score in scores:
            if isinstance(colors, dict):
                _letterAt(base, x, y, score, ax, globscale, LETTERS, colors)
            else:
                _letterAt(base, x, y, score, ax, globscale, LETTERS,
                          color_scheme(colors))
            y += score
        x += 1
        maxi = max(maxi, y)

    return ax2
Exemplo n.º 14
0
def plotDataV2(df, i):
    xrange = np.arange(60 * 24)

    plotdf = pd.DataFrame()
    for group in df.groupby([df.device_id]):
        groupdf = pd.DataFrame()
        groupdf[group[0]] = group[1]['mean']

        # FIXME remove the follwing three lines - no longer needed, the missing values are filled on compute_amvd.py now
        # groupdf[group[0]+'-minute'] = group[1]['minute']
        # groupdf[group[0]+'-minute'] = group[1]['timestamp']*60 + group[1]['timestamp.1']
        # groupdf = groupdf.set_index(group[0]+'-minute').reindex(xrange).fillna(0).reset_index()

        plotdf[group[0]] = groupdf[group[0]].values
        plotdf[group[0] + '-delta'] = group[1]['delta'].values
        plotdf[group[0] + '-activity'] = group[1]['activity_name'].values

    fig, ax = plt.subplots()
    #fig.canvas.set_window_title('Day '+str(i))
    ax.set_title('Click on legend line to toggle line on/off')
    lines = []
    for column in plotdf.columns:
        if 'delta' in column or 'activity' in column:
            continue
        line, = ax.plot(xrange,
                        plotdf[column],
                        lw=1.5,
                        label=column,
                        linestyle='-',
                        marker=',',
                        markersize=5)
        # new
        activity_groups = plotdf[column + '-activity'].groupby(
            plotdf[column + '-activity'])
        activity_labels_arr = []
        for name, group in activity_groups:
            if name == '0':
                continue
            print column, group.index
            yvals = plotdf.iloc[group.index]
            activity_labels, = ax.plot(group.index,
                                       yvals[column],
                                       marker=TextPath((0, 0),
                                                       name[0],
                                                       size=10000),
                                       color='black',
                                       linestyle='',
                                       ms=10,
                                       label='_nolegend_')
            activity_labels_arr.append(activity_labels)
        # new end
        # poly = ax.fill_between(xrange, plotdf[column], where=plotdf[column]>10.05, facecolor=line.get_color(), alpha=0.5)
        poly = ax.fill_between(
            xrange,
            plotdf[column],
            where=(plotdf[column] > config['magnitude_threshold']).values &
            (plotdf[column + '-delta'].abs() >
             config['delta_threshold']).values,
            facecolor=line.get_color(),
            alpha=0.5)
        lines.append(
            (line, poly,
             activity_labels_arr))  # 0 is the line, 1 is the filled polygon

    # set x axis to display time
    def timeformatter(x, pos):
        'The two args are the value and tick position'
        return "{:02d}:{:02d}".format(int(x) / 60, int(x) % 60)

    formatter = plt.FuncFormatter(timeformatter)
    ax.xaxis.set_major_formatter(formatter)

    # set axis names
    plt.xlabel('Time')
    plt.ylabel('Acceleration(magnitude)')

    leg = ax.legend(loc='upper left', fancybox=True, shadow=True)
    leg.get_frame().set_alpha(0.4)
    lined = dict()
    for legline, origline in zip(leg.get_lines(), lines):
        legline.set_picker(5)  # 5 pts tolerance
        lined[legline] = origline

    def onpick(event):
        # on the pick event, find the orig line corresponding to the
        # legend proxy line, and toggle the visibility
        legline = event.artist
        origline = lined[legline][0]  # 0 is the line, 1 is the filled polygon
        poly = lined[legline][1]
        vis = not origline.get_visible()
        origline.set_visible(vis)
        poly.set_visible(vis)
        # new
        activity_labels_arr = lined[legline][2]
        for activity_labels in activity_labels_arr:
            activity_labels.set_visible(vis)
        # new end

        # Change the alpha on the line in the legend so we can see what lines
        # have been toggled
        if vis:
            legline.set_alpha(1.0)
        else:
            legline.set_alpha(0.2)
        fig.canvas.draw()

    fig.canvas.mpl_connect('pick_event', onpick)
def plot_own_sequence_logo(ALL_SCORES):
    # ALL_SCORES = [[('A', 0),
    #                 ('C', 1),
    #                 ('G', 1),
    #                 ('T', 0.0)],
    #                [('C', 1),
    #                 ('G', 1),
    #                 ('A', 0),
    #                 ('T', 0)]]
    # NOTE: order MATTERS within each row - smallest probability should appear first

    fp = FontProperties(family="Arial", weight="bold")
    globscale = 1.35
    LETTERS = {
        "T": TextPath((-0.305, 0), "T", size=1, prop=fp),
        "G": TextPath((-0.384, 0), "G", size=1, prop=fp),
        "A": TextPath((-0.35, 0), "A", size=1, prop=fp),
        "C": TextPath((-0.366, 0), "C", size=1, prop=fp)
    }
    COLOR_SCHEME = {'G': 'orange', 'A': 'green', 'C': 'blue', 'T': 'red'}

    def letterAt(letter, x, y, yscale=1, ax=None):
        text = LETTERS[letter]

        t = mpl.transforms.Affine2D().scale(1 * globscale, yscale * globscale) + \
            mpl.transforms.Affine2D().translate(x, y) + ax.transData
        p = PathPatch(text, lw=0, fc=COLOR_SCHEME[letter], transform=t)
        if ax != None:
            ax.add_artist(p)
        return p

    import matplotlib.pyplot as plt

    fig, ax = plt.subplots(figsize=(10, 3))

    all_scores = ALL_SCORES
    x = 1
    maxi = 0
    for scores in all_scores:
        y = 0
        for base, score in scores:
            letterAt(base, x, y, score, ax)
            y += score
        x += 1
        maxi = max(maxi, y)

    # plt.rcParams['axes.labelweight'] = 'bold'
    plt.rcParams['axes.linewidth'] = 1.2
    plt.ylabel("bits", weight='bold')
    plt.xticks(range(1, x), weight='bold')
    plt.yticks([0, 1, 2], weight='bold')
    plt.xlim((0.5, x - 0.5))
    plt.ylim((0, 2))  #maxi

    ax.tick_params(length=0.0)

    # rc('axes', linewidth=2)
    # rc('font', weight='bold')

    # ax.spines['bottom'].set_visible(False)
    # Hide the right and top spines
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)

    # Only show ticks on the left and bottom spines
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
    plt.tight_layout()
    plt.show()
Exemplo n.º 16
0
def sequence_logo(score_matrix,
                  order="value",
                  width=1.0,
                  ax=None,
                  sequence_type=Genome,
                  font_properties=None,
                  color_scheme=None,
                  **kwargs):
    """Plots a sequence logo for visualizing motifs.

    Parameters
    ----------
    score_matrix : np.ndarray
        An :math:`L \\times N` array (where :math:`L` is the length of
        the sequence, and :math:`N` is the size of the alphabet)
        containing the scores for each base occuring at each position.
    order : {'alpha', 'value'}
        The manner by which to sort the bases stacked at each position
        in the sequence logo plot.

            * 'alpha' - Bases go in the order they are found in the\
                      sequence alphabet.
            * 'value' - Bases go in the order of their value, with the\
                        largest at the bottom.
    width : float, optional
        Default is 1. The width of each character in the plotted logo.
        A value of 1 will mean that there is no gap between each the
        characters at each position. A value of 0 will not draw any
        characters.
    ax : matplotlib.pyplot.Axes or None, optional
        Default is `None`. The axes to plot on. If left as `None`, a new
        axis will be created.
    sequence_type : class, optional
        Default is `selene_sdk.sequences.Genome`. The type of sequence that
        the *in silico* mutagenesis results are associated with. This
        should generally be a subclass of `selene_sdk.sequences.Sequence`.
    font_properties : matplotlib.font_manager.FontProperties or None, optional
        Default is `None`. A `matplotlib.font_manager.FontProperties`
        object that specifies the properties of the font to use for
        plotting the motif. If `None`, no font will be used, and the
        text will be rendered by a path. This method of rendering paths
        is  preferred, as it ensures all character heights correspond to
        the actual values, and that there are no extra gaps between
        the tops and bottoms of characters at each position in the
        sequence logo. If the user opts to use a value other
        than `None`, then no such guarantee can be made.
    color_scheme : list(str) or None, optional
        Default is `None`. A list containing the hex codes or names of
        colors to use, appearing in the order of the bases of the
        sequence type. If left as `None`, a default palette will be made
        with `seaborn.color_palette`, and will have as many
        colors as there are characters in the input sequence alphabet.

    Returns
    -------
    matplotlib.pyplot.Axes
        The axes containing the sequence logo plot.

    Raises
    ------
    ValueError
        If the number of columns in `score_matrix` does not match the
        number of characters in the alphabet of `sequence_type`.

    ValueError
        If the number of colors in `color_palette` does not match the
        number of characters in the alphabet of `sequence_type`.

    Examples
    --------
    We have included an example of the output from a`sequence_logo`
    plot below:

    .. image:: ../../docs/source/_static/img/sequence_logo_example.png

    """
    # Note that everything will break if we do not deepcopy.
    score_matrix = deepcopy(score_matrix)

    score_matrix = score_matrix.transpose()
    if font_properties is not None:
        warnings.warn(
            "Specifying a value for `font_properties` (other than `None`) "
            "will use the `matplotlib`-based character paths, and causes "
            "distortions in the plotted motif. We recommend leaving "
            "`font_properties=None`. See the documentation for details.",
            UserWarning)

    if color_scheme is None:
        color_scheme = sns.color_palette("Set1",
                                         n_colors=len(sequence_type.BASES_ARR))
        color_scheme = color_scheme.as_hex()
    if len(color_scheme) < len(sequence_type.BASES_ARR):
        raise ValueError(
            "Color scheme is shorter than number of bases in sequence.")

    if score_matrix.shape[0] != len(sequence_type.BASES_ARR):
        raise ValueError(
            "Got score with {0} bases for sequence with {1} bases.".format(
                score_matrix.shape[0], len(sequence_type.BASES_ARR)))
    if ax is None:
        _, ax = plt.subplots(figsize=score_matrix.shape)

    # Determine offsets depending on sort order.
    positive_offsets = np.zeros_like(score_matrix)
    negative_offsets = np.zeros_like(score_matrix)
    bases = np.empty(score_matrix.shape, dtype=object)
    bases[:, :] = "?"  # This ensures blanks are visually obvious.

    # Change ordering of things based on input arguments.
    if order == "alpha":
        for i in range(score_matrix.shape[0]):
            bases[i, :] = sequence_type.BASES_ARR[i]

    elif order == "value":
        if np.sum(score_matrix < 0) != 0:
            sorted_scores = np.zeros_like(score_matrix)
            for j in range(score_matrix.shape[1]):
                # Sort the negative values and put them at bottom.
                div = np.sum(score_matrix[:, j] < 0.)
                negative_idx = np.argwhere(score_matrix[:, j] < 0.).flatten()
                negative_sort_idx = np.argsort(score_matrix[negative_idx, j],
                                               axis=None)
                sorted_scores[:div, j] = score_matrix[
                    negative_idx[negative_sort_idx], j]
                bases[:div, j] = sequence_type.BASES_ARR[
                    negative_idx[negative_sort_idx]].flatten()

                # Sort the positive values and stack atop the negatives.
                positive_idx = np.argwhere(score_matrix[:, j] >= 0.).flatten()
                positive_sort_idx = np.argsort(score_matrix[positive_idx, j],
                                               axis=None)
                sorted_scores[div:, j] = score_matrix[
                    positive_idx[positive_sort_idx], j]
                bases[div:, j] = sequence_type.BASES_ARR[
                    positive_idx[positive_sort_idx]].flatten()
            score_matrix = sorted_scores
        else:
            for j in range(score_matrix.shape[1]):
                sort_idx = np.argsort(score_matrix[:, j], axis=None)[::-1]
                bases[:, j] = sequence_type.BASES_ARR[sort_idx]
                score_matrix[:, j] = score_matrix[sort_idx, j]

    # Create offsets for each bar.
    for i in range(score_matrix.shape[0] - 1):
        y_coords = score_matrix[i, :]
        if i > 0:
            negative_offsets[i + 1, :] = negative_offsets[i, :]
            positive_offsets[i + 1, :] = positive_offsets[i, :]
        neg_idx = np.argwhere(y_coords < 0.)
        pos_idx = np.argwhere(y_coords >= 0.)
        negative_offsets[i + 1, neg_idx] += y_coords[neg_idx]
        positive_offsets[i + 1, pos_idx] += y_coords[pos_idx]

    for i in range(score_matrix.shape[0]):
        x_coords = np.arange(score_matrix.shape[1]) + 0.5
        y_coords = score_matrix[i, :]

        # Manage negatives and positives separately.
        offsets = np.zeros(score_matrix.shape[1])
        negative_idx = np.argwhere(y_coords < 0.)
        positive_idx = np.argwhere(y_coords >= 0.)
        offsets[negative_idx] = negative_offsets[i, negative_idx]
        offsets[positive_idx] = positive_offsets[i, positive_idx]
        bars = ax.bar(x_coords,
                      y_coords,
                      color="black",
                      width=width,
                      bottom=offsets)
        for j, bar in enumerate(bars):
            base = bases[i, j]
            bar.set_color(color_scheme[sequence_type.BASE_TO_INDEX[base]])
            bar.set_edgecolor(None)

    # Iterate over the barplot's bars and turn them into letters.
    new_patches = []
    for i, bar in enumerate(ax.patches):
        base_idx = i // score_matrix.shape[1]
        seq_idx = i % score_matrix.shape[1]
        base = bases[base_idx, seq_idx]
        # We construct a text path that tracks the bars in the barplot.
        # Thus, the barplot takes care of scaling and translation,
        #  and we just copy it.
        if font_properties is None:
            text = Path(_SVG_PATHS[base][0], _SVG_PATHS[base][1])
        else:
            text = TextPath((0., 0.), base, fontproperties=font_properties)
        b_x, b_y, b_w, b_h = bar.get_extents().bounds
        t_x, t_y, t_w, t_h = text.get_extents().bounds
        scale = (b_w / t_w, b_h / t_h)
        translation = (b_x - t_x, b_y - t_y)
        text = PathPatch(text, facecolor=bar.get_facecolor(), lw=0.)
        bar.set_facecolor("none")
        text.set_path_effects([_TextPathRenderingEffect(bar)])
        transform = transforms.Affine2D().translate(*translation).scale(*scale)
        text.set_transform(transform)
        new_patches.append(text)

    for patch in new_patches:
        ax.add_patch(patch)
    ax.set_xlim(0, score_matrix.shape[1])
    ax.set_xticks(np.arange(score_matrix.shape[1]) + 0.5)
    ax.set_xticklabels(np.arange(score_matrix.shape[1]))
    return ax
Exemplo n.º 17
0
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.text import TextPath
from matplotlib.transforms import Affine2D


def text3d(ax, (x, y, z), s, zdir="z", size=None, angle=0, usetex=False,
           **kwargs):

    if zdir == "y":
        xy1, z1 = (x, z), y
    elif zdir == "y":
        xy1, z1 = (y, z), x
    else:
        xy1, z1 = (x, y), z

    text_path = TextPath((0, 0), s, size=size, usetex=usetex)
    trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])

    p1 = PathPatch(trans.transform_path(text_path), **kwargs)
    ax.add_patch(p1)
    art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

p = Circle((5, 5), 3)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")

Exemplo n.º 18
0
import matplotlib.patches as patches
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from matplotlib.font_manager import FontProperties
import numpy as np
from scipy import stats

import pyproteome as pyp
from . import motif, plogo

BASES = list('ACDEFGHIKLMNPQRSTVWY')
GLOBSCALE = 1.4
LETTERS = {
    base: TextPath(
        (-0.303, 0),
        base,
        size=1,
        prop=FontProperties(family='monospace', weight='bold'),
    )
    for base in BASES
}
LETTERS['Q'] = TextPath(
    (-0.303, .11),
    'Q',
    size=1,
    prop=FontProperties(family='monospace', weight='bold'),
)
LETTERS['G'] = TextPath(
    (-0.303, .01),
    'G',
    size=1,
    prop=FontProperties(family='monospace', weight='bold'),
Exemplo n.º 19
0
def logo_plot(df,
              seqID,
              refseq=True,
              key_residues=None,
              line_break=None,
              font_size=35,
              colors="WEBLOGO"):
    """Generates classic **LOGO** plots.

    :param df: Data container.
    :type df: Union[:class:`.DesignFrame`, :class:`.SequenceFrame`]
    :param str seqID: |seqID_param|.
    :param bool refseq: if :data:`True` (default), mark the original residues according to
        the reference sequence.
    :param key_residues: |keyres_param|.
    :type key_residue: |keyres_param|
    :param int line_break: Force a line-change in the plot after n residues are plotted.
    :param float font_size: Expected size of the axis font.
    :param colors: Colors to assign; it can be the name of a available color set or
        a dictionary with a color for each type.
    :type colors: Union[:class:`str`, :class:`dict`]

    :return: :class:`~matplotlib.figure.Figure` and
        :func:`list` of :class:`~matplotlib.axes.Axes`

    .. rubric:: Example

    .. ipython::

        In [1]: from rstoolbox.io import parse_rosetta_file
           ...: from rstoolbox.plot import logo_plot
           ...: import matplotlib.pyplot as plt
           ...: df = parse_rosetta_file("../rstoolbox/tests/data/input_2seq.minisilent.gz",
           ...:                         {"sequence": "B"})
           ...: df.add_reference_sequence("B", df.get_sequence("B")[0])
           ...: fig, axes = logo_plot(df, "B", refseq=True, line_break=50)
           ...: plt.tight_layout()

        @savefig sequence_logo_plot_docs.png width=5in
        In [2]: plt.show()
    """
    def _letterAt(letter,
                  x,
                  y,
                  yscale=1,
                  ax=None,
                  globscale=1.35,
                  LETTERS=None,
                  COLOR_SCHEME=None):
        text = LETTERS[letter]
        t = mpl.transforms.Affine2D().scale(1 * globscale, yscale * globscale) + \
            mpl.transforms.Affine2D().translate(x, y) + ax.transData
        p = PathPatch(text, lw=0, fc=COLOR_SCHEME[letter], transform=t)
        if ax is not None:
            ax.add_artist(p)
        return p

    def _dataframe2logo(data):
        aa = list(data)
        odata = []
        for _, pos in data.iterrows():
            pdata = []
            for k in aa:
                if pos[k] > 0.0000000:
                    pdata.append((k, float(pos[k])))
            odata.append(sorted(pdata, key=operator.itemgetter(1, 0)))
        return odata

    def _chunks(l, n):
        for i in range(0, len(l), n):
            yield l[i:i + n]

    order = [
        "A", "V", "I", "L", "M", "F", "Y", "W", "S", "T", "N", "Q", "R", "H",
        "K", "D", "E", "C", "G", "P"
    ]
    data = copy.deepcopy(df)

    mpl.rcParams['svg.fonttype'] = 'none'
    # Graphical Properties of resizable letters
    path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                        '../components/square.ttf')
    fp = FontProperties(fname=path, weight="bold")
    globscale = 1.22
    letters_shift = -0.5
    LETTERS = {}
    for aa in color_scheme(colors):
        LETTERS[aa] = TextPath((letters_shift, 0), aa, size=1, prop=fp)

    # Data type management.
    if not isinstance(data, pd.DataFrame):
        raise ValueError(
            "Input data must be in a DataFrame, DesignFrame or SequenceFrame")
    else:
        if not isinstance(data, (DesignFrame, SequenceFrame)):
            if len(set(data.columns.values).intersection(
                    set(order))) == len(order):
                data = SequenceFrame(data)
            else:
                data = DesignFrame(data)
    if isinstance(data, DesignFrame):
        data = data.sequence_frequencies(seqID)

    # key_residues management.
    length = len(data.get_reference_sequence(seqID)) if refseq else None
    key_residues = get_selection(key_residues, seqID, list(data.index.values),
                                 length)

    # Plot
    if line_break is None:
        figsize = (len(data) * 2, 2.3 * 2)
        grid = (1, 1)
        fig = plt.figure(figsize=figsize)
        axs = [
            plt.subplot2grid(grid, (0, 0)),
        ]
        krs = [
            key_residues,
        ]
    else:
        rows = int(math.ceil(float(len(data)) / line_break))
        figsize = (float(len(data) * 2) / rows, 2.3 * 2 * rows)
        grid = (rows, 1)
        fig = plt.figure(figsize=figsize)
        axs = [plt.subplot2grid(grid, (_, 0)) for _ in range(rows)]
        krs = list(_chunks(key_residues, line_break))

    font = FontProperties()
    font.set_size(font_size)
    font.set_weight('bold')

    for _, ax in enumerate(axs):
        # Refseq and key_residues management.
        ref_seq = data.get_reference_sequence(seqID, krs[_]) if refseq else ""
        # data and key_residues management.
        _data = data.get_key_residues(krs[_])

        maxv = int(math.ceil(data.max_hight()))

        ticks = len(_data)
        if line_break is not None and len(_data) < line_break:
            ticks = line_break
        ax.set_xticks(np.arange(0.5, ticks + 1))
        ax.set_yticks(range(0, maxv + 1))
        ax.set_xticklabels(_data.index.values)
        ax.set_yticklabels(np.arange(0, maxv + 1, 1))
        if ref_seq is not None:
            ax2 = ax.twiny()
            ax2.set_xticks(ax.get_xticks())
            ax2.set_xticklabels(list(ref_seq))
        sns.despine(ax=ax, trim=True)
        ax.grid(False)
        if ref_seq is not None:
            sns.despine(ax=ax2, top=False, right=True, left=True, trim=True)
            ax2.grid(False)
        ax.lines = []
        wdata = _dataframe2logo(_data)
        x = 0.5
        maxi = 0
        for scores in wdata:
            y = 0
            for base, score in scores:
                _letterAt(base, x, y, score, ax, globscale, LETTERS,
                          color_scheme(colors))
                y += score
            x += 1
            maxi = max(maxi, y)
        for label in (ax.get_xticklabels() + ax.get_yticklabels()):
            label.set_fontproperties(font)
        if ref_seq is not None:
            for label in (ax2.get_xticklabels() + ax2.get_yticklabels()):
                label.set_fontproperties(font)

    return fig, axs
Exemplo n.º 20
0
 def dna_logo(self, save=False, show=False, count=True, ax=None):
     freq = np.array(self._freq(count))
     en = 2.88539008 / max(sum(self.count), 1.5)
     info = (np.log(5) / np.log(2) - en - self.entropy(count=count))
     if np.min(info) < 0:
         info -= np.min(info)
     height = (freq.T * info).T
     order = ['A', 'G', 'C', 'T', '-']
     height = [
         sorted(list(zip(order, i)), key=lambda x: x[1]) for i in height
     ]
     fp = FontProperties(family="monospace", weight="bold")
     LETTERS = {
         "T": TextPath((-0.395, 0), "T", size=1.35, prop=fp),
         "G": TextPath((-0.395, 0), "G", size=1.35, prop=fp),
         "A": TextPath((-0.395, 0), "A", size=1.35, prop=fp),
         "C": TextPath((-0.395, 0), "C", size=1.35, prop=fp),
         "-": TextPath((-0.395, 0), "I", size=1.35, prop=fp)
     }
     COLOR_SCHEME = {
         'G': 'orange',
         'A': 'red',
         'C': 'blue',
         'T': 'darkgreen',
         '-': 'black'
     }
     if ax:
         ax = ax
         drawx = False
         fig = None
     else:
         fig = Figure(figsize=(7, 2))
         ax = fig.subplots()
         drawx = True
     for x, scores in enumerate(height):
         y = 0
         for letter, score in scores:
             text = LETTERS[letter]
             t = mpl.transforms.Affine2D().scale(1.2, score) + \
                 mpl.transforms.Affine2D().translate(x+1, y) + ax.transData
             p = PathPatch(text, lw=0, fc=COLOR_SCHEME[letter], transform=t)
             ax.add_artist(p)
             y += score
     x_tick_label = ([
         str(k + 1) + '\n' + i[-1][0] for k, i in enumerate(height)
     ] if drawx else [str(k + 1) for k, i in enumerate(height)])
     ax.set_title('{} Total count: {}'.format(str(self.name),
                                              sum(self.count)),
                  fontsize=6)
     ax.set_xticks(range(1, len(height) + 1), )
     ax.set_xticklabels(x_tick_label)
     ax.set_xlim((0, len(height) + 1))
     ax.set_ylim((0, 2.33))
     ax.tick_params(axis='both', which='both', labelsize=6)
     if save:
         fig.set_tight_layout(True)
         save = save if isinstance(save,
                                   str) else str(self.name) + '_logo.svg'
         fig.savefig(save, format='svg')
     if show:
         plt.tight_layout()
         plt.show()
     return fig
Exemplo n.º 21
0
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import matplotlib.patheffects
from matplotlib import transforms
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from matplotlib.font_manager import FontProperties

"""
Global variables for plotting logos
"""

fp = FontProperties(family="Arial", weight="bold") 
GLOBSCALE = 1.35
LETTERS = { "T" : TextPath((-0.305, 0), "T", size=1, prop=fp),
            "G" : TextPath((-0.384, 0), "G", size=1, prop=fp),
            "A" : TextPath((-0.35, 0), "A", size=1, prop=fp),
            "C" : TextPath((-0.366, 0), "C", size=1, prop=fp) }
COLOR_SCHEME = {'G': 'orange', 
                'A': 'red', 
                'C': 'blue', 
                'T': 'darkgreen'}

class Scale(matplotlib.patheffects.RendererBase):
    def __init__(self, sx, sy=None):
        self._sx = sx
        self._sy = sy

    def draw_path(self, renderer, gc, tpath, affine, rgbFace):
        affine = affine.identity().scale(self._sx, self._sy)+affine
Exemplo n.º 22
0
 def get_letter_to_glyph(self):
     # preferably Arial, but that requires separate installation
     fp = FontProperties(family="sans", weight="bold")
     letters = dict(A=TextPath((-0.35, 0), "A", size=1, prop=fp),
                    C=TextPath((-0.35, 0), "C", size=1, prop=fp),
                    D=TextPath((-0.36, 0), "D", size=1, prop=fp),
                    E=TextPath((-0.34, 0), "E", size=1, prop=fp),
                    F=TextPath((-0.32, 0), "F", size=1, prop=fp),
                    G=TextPath((-0.378, 0), "G", size=1, prop=fp),
                    H=TextPath((-0.36, 0), "H", size=1, prop=fp),
                    I=TextPath((-0.14, 0), "I", size=1, prop=fp),
                    K=TextPath((-0.39, 0), "K", size=1, prop=fp),
                    L=TextPath((-0.33, 0), "L", size=1, prop=fp),
                    M=TextPath((-0.41, 0), "M", size=1, prop=fp),
                    N=TextPath((-0.36, 0), "N", size=1, prop=fp),
                    P=TextPath((-0.345, 0), "P", size=1, prop=fp),
                    Q=TextPath((-0.392, 0), "Q", size=1, prop=fp),
                    R=TextPath((-0.385, 0), "R", size=1, prop=fp),
                    S=TextPath((-0.32, 0), "S", size=1, prop=fp),
                    T=TextPath((-0.31, 0), "T", size=1, prop=fp),
                    V=TextPath((-0.33, 0), "V", size=1, prop=fp),
                    W=TextPath((-0.47, 0), "W", size=1, prop=fp),
                    Y=TextPath((-0.33, 0), "Y", size=1, prop=fp))
     return letters
Exemplo n.º 23
0
def _protein_letter_at(letter, x, y, yscale=1, ax=None, color='black', alpha=1.0):

    #fp = FontProperties(family="Arial", weight="bold")
    #fp = FontProperties(family="Ubuntu", weight="bold")
    fp = FontProperties(family="DejaVu Sans", weight="bold")

    globscale = 1.35
    LETTERS = {"T" : TextPath((-0.305, 0), "T", size=1, prop=fp),
               "G" : TextPath((-0.384, 0), "G", size=1, prop=fp),
               "A" : TextPath((-0.35, 0), "A", size=1, prop=fp),
               "C" : TextPath((-0.366, 0), "C", size=1, prop=fp),

               "L" : TextPath((-0.35, 0), "L", size=1, prop=fp),
               "M" : TextPath((-0.35, 0), "M", size=1, prop=fp),
               "F" : TextPath((-0.35, 0), "F", size=1, prop=fp),
               "W" : TextPath((-0.35, 0), "W", size=1, prop=fp),
               "K" : TextPath((-0.35, 0), "K", size=1, prop=fp),
               "Q" : TextPath((-0.35, 0), "Q", size=1, prop=fp),
               "E" : TextPath((-0.35, 0), "E", size=1, prop=fp),
               "S" : TextPath((-0.35, 0), "S", size=1, prop=fp),
               "P" : TextPath((-0.35, 0), "P", size=1, prop=fp),
               "V" : TextPath((-0.35, 0), "V", size=1, prop=fp),
               "I" : TextPath((-0.35, 0), "I", size=1, prop=fp),
               "Y" : TextPath((-0.35, 0), "Y", size=1, prop=fp),
               "H" : TextPath((-0.35, 0), "H", size=1, prop=fp),
               "R" : TextPath((-0.35, 0), "R", size=1, prop=fp),
               "N" : TextPath((-0.35, 0), "N", size=1, prop=fp),
               "D" : TextPath((-0.35, 0), "D", size=1, prop=fp),
               "U" : TextPath((-0.35, 0), "U", size=1, prop=fp),
               "!" : TextPath((-0.35, 0), "!", size=1, prop=fp),

               "UP" : TextPath((-0.488, 0), '$\\Uparrow$', size=1, prop=fp),
               "DN" : TextPath((-0.488, 0), '$\\Downarrow$', size=1, prop=fp),
               "(" : TextPath((-0.25, 0), "(", size=1, prop=fp),
               "." : TextPath((-0.125, 0), "-", size=1, prop=fp),
               ")" : TextPath((-0.1, 0), ")", size=1, prop=fp)}


    if letter in LETTERS :
        text = LETTERS[letter]
    else :
        text = TextPath((-0.35, 0), letter, size=1, prop=fp)

    chosen_color = color

    if chosen_color is None :
        chosen_color = 'black'
        if letter in ['A', 'I', 'L', 'M', 'F', 'W', 'V'] : #Hydrophobic
            chosen_color = 'blue'
        elif letter in ['K' ,'R'] : #Positive charge
            chosen_color = 'red'
        elif letter in ['E', 'D'] : #Negative charge
            chosen_color = 'magenta'
        elif letter in ['N', 'Q', 'S', 'T'] : #Polar
            chosen_color = 'green'
        elif letter in ['C'] : #Cysteines
            chosen_color = 'pink'
        elif letter in ['G'] : #Glycines
            chosen_color = 'orange'
        elif letter in ['P'] : #Prolines
            chosen_color = 'yellow'
        elif letter in ['H', 'Y'] : #Aromatic
            chosen_color = 'cyan'

    t = mpl.transforms.Affine2D().scale(1*globscale, yscale*globscale) + \
        mpl.transforms.Affine2D().translate(x,y) + ax.transData
    p = PathPatch(text, lw=0, fc=chosen_color, alpha=alpha, transform=t)
    if ax != None:
        ax.add_artist(p)
    return p
Exemplo n.º 24
0
def text_path(name):
    return TextPath((0, 0), get_id(name))
                   (0.6, 0.8, 0.8), (1.0, 1.0, 1.0))}
# color map: field lines (red | blue)
redbl = {'red': ((0., 1., 1.), (0.5, 1., 0.), (1., 0., 0.)),
         'blue': ((0., 0., 0.), (0.5, 0., 1.), (1., 1., 1.)),
         'green': ((0., 0., 0.), (1., 0., 0.)),
         'alpha': ((0., 0.4, 0.4), (1., 0.4, 0.4))}
mne_field_grad_cols = LinearSegmentedColormap('mne_grad', yrtbc)
mne_field_line_cols = LinearSegmentedColormap('mne_line', redbl)

# plot gradient and contour lines
im = plt.imshow(Z, cmap=mne_field_grad_cols, aspect='equal')
cs = plt.contour(Z, 9, cmap=mne_field_line_cols, linewidths=1)
plot_dims = np.r_[np.diff(ax.get_xbound()), np.diff(ax.get_ybound())]

# create MNE clipping mask
mne_path = TextPath((0, 0), 'MNE')
dims = mne_path.vertices.max(0) - mne_path.vertices.min(0)
vert = mne_path.vertices - dims / 2.
mult = (plot_dims / dims).min()
mult = [mult, -mult]  # y axis is inverted (origin at top left)
offset = plot_dims / 2. - center_fudge
mne_clip = Path(offset + vert * mult, mne_path.codes)
# apply clipping mask to field gradient and lines
im.set_clip_path(mne_clip, transform=im.get_transform())
for coll in cs.collections:
    coll.set_clip_path(mne_clip, transform=im.get_transform())
# get final position of clipping mask
mne_corners = mne_clip.get_extents().corners()

# add tagline
rcParams.update({'font.sans-serif': ['Cooper Hewitt'], 'font.weight': 'light'})
Exemplo n.º 26
0
import matplotlib as mpl
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from matplotlib.font_manager import FontProperties

fp = FontProperties(family="Arial", weight="bold") 
globscale = 1.35
NUMBERS = { "1" : TextPath((-0.30, 0), "1", size=1, prop=fp),
            "3" : TextPath((-0.305, 0), "3", size=1, prop=fp),
            "5" : TextPath((-0.35, 0), "5", size=1, prop=fp),
            "7" : TextPath((-0.366, 0), "7", size=1, prop=fp),
            "9" : TextPath((-0.384, 0), "9", size=1, prop=fp),
            "11" : TextPath((-0.398, 0), "E", size=1, prop=fp) }

ALPHABETS = { "A" : TextPath((-0.305, 0), "A", size=1, prop=fp),
            "T" : TextPath((-0.35, 0), "T", size=1, prop=fp),
            "G" : TextPath((-0.366, 0), "G", size=1, prop=fp),
            "C" : TextPath((-0.384, 0), "C", size=1, prop=fp) }


COLOR_SCHEME = {'1': 'yellow',
                '3': 'orange', 
                '5': 'red', 
                '7': 'blue', 
                '9': 'navy',
                '11': 'darkgreen'}

COLOR_SCHEME_ALPHABET = {'A': 'darkgreen', 
                'T': 'red', 
                'G': 'orange', 
                'C': 'navy'}
    ax1.axis('off')
except:
    print('image missing')

# Scatter plot
ax2 = fig.add_subplot(1, 2, 2)
ax2.plot(df_red['x'], df_red['y'], ".", label='Red', color='r')
ax2.plot(df_green['x'], df_green['y'], ".", label='Green', color='g')
ax2.plot(df_blue['x'], df_blue['y'], ".", label='Blue', color='b')
ax2.plot(df_yellow['x'], df_yellow['y'], ".", label='Yellow', color='y')

#Candidates
for c in candidates:
    ax2.plot(c[1],
             c[2],
             marker=TextPath((0, 0), c[0]),
             markersize=20,
             color='k')

ax2.set_xlim(-10, 10)
ax2.set_ylim(-10, 10)
ax2.set_title('Political Compass')
ax2.set_xlabel('Planned Economy  <--  Economics  -->  Free Market')
ax2.set_ylabel('Liberal  <-- Government  --> Authoritarian')
lgd2 = ax2.legend(loc=1)
fig.savefig("Simulated_Spectrum", dpi=300)

if centerists:
    mean_center = [0, 0]
    cov_center = [[5, 0], [0, 5]]  # diagonal covariance
    pos_center = np.random.multivariate_normal(mean_center, cov_center, 3500)
Exemplo n.º 28
0
E_data_extra = E_data_extra.sort_index()
E_data_extra2 = E_data_extra2.sort_index()
E_data_extra2.to_excel(writer, "E_PV_PC")


fig = plt.figure(num=None, figsize=(8, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace=0.3, wspace=0.3)
i=0
for ttype, v1 in E_data.items():
    i += 1
    ax = fig.add_subplot(2, math.ceil(len(E_data)/2), i)
    for product, v2 in v1.items():
        search = re.search(r"^(\w)Z(\d+)$", product, re.IGNORECASE).groups()
        char = search[0]
        label= iden_label(int(search[1]))
        label = TextPath((0,0), str(char+label), linewidth=3)
        linestyle = iden_company(char)
        ax.plot(v2["x"], v2["y"], label=product, linestyle=linestyle, marker=label, markersize=20)
        ax.set_title(ttype)
    plt.xlim([x_lower,x_upper])
    ax.set_xlabel('Period')
    ax.set_ylabel(v2["unit"])
handles, labels = ax.get_legend_handles_labels()
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
fig.legend(handles, labels, loc='lower right')
fig.suptitle('E. Product Sales', fontsize=20)
fig.savefig(rpt_out+'/E.png')

# Deal with F for competitive
F_data = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(dict)))
F_data2 = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(dict)))
Exemplo n.º 29
0
if 1:

    usetex = plt.rcParams["text.usetex"]

    fig = plt.figure(1)

    # EXAMPLE 1

    ax = plt.subplot(211)

    from matplotlib._png import read_png
    fn = get_sample_data("grace_hopper.png", asfileobj=False)
    arr = read_png(fn)

    text_path = TextPath((0, 0), "!?", size=150)
    p = PathClippedImagePatch(text_path,
                              arr,
                              ec="k",
                              transform=IdentityTransform())

    #p.set_clip_on(False)

    # make offset box
    offsetbox = AuxTransformBox(IdentityTransform())
    offsetbox.add_artist(p)

    # make anchored offset box
    ao = AnchoredOffsetbox(loc=2, child=offsetbox, frameon=True, borderpad=0.2)
    ax.add_artist(ao)
Exemplo n.º 30
0
    list.sort(key=sortSecond)  
    PPM.append(list)

PPM

    
# draw the floating letters graph
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
#...


fig, ax = plt.subplots(figsize=(20,10))

for b in baseline:
    path = TextPath((0,0), b[0])
    plt.plot(b[1],b[2],marker=path, alpha=1, markersize=50, color=b[3])

for i in line_0:
    path = TextPath((0,0), i[0])
    plt.plot(i[1],i[2],marker=path, alpha=1, markersize=50, color=i[3])

for k in line_1:
    path = TextPath((0,0), k[0])
    plt.plot(k[1],k[2],marker=path, alpha=1, markersize=50, color=k[3])

for t in line_2:
    path = TextPath((0,0), t[0])
    plt.plot(t[1],t[2],marker=path, alpha=1, markersize=50, color=t[3])

plt.xlim([-11,11])