sequence logos in matplotlib: aligning xticks

前端 未结 3 1520
死守一世寂寞
死守一世寂寞 2020-12-03 13:14

I am trying to draw sequence logos using matplotlib. The entire code is available on gist

The relevant portion is:

class Scale(matplotlib.patheffects         


        
3条回答
  •  难免孤独
    2020-12-03 13:25

    I would suggest to work in data coordinates and unit coordinates throughout the script.

    gact.py
    Script to plot a letter at a given position with a given scale. One obstacle is that the letters created by TextPath have their lower left corner at relative position (0,0) and that they don't span the complete range up to (1,1). We therefore need to shift the TextPath to the left such that the lower center of the letter is at (0,0) and introduce a globscale scaling parameter, which makes the letter 1 unit in height. Unfortunately this depends on the font being used, so for a different font, one has to adapt the x coordinate and the globscale parameter again.

    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
    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'}
    
    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
    

    running code

    import matplotlib.pyplot as plt
    import gact
    
    fig, ax = plt.subplots(figsize=(10,3))
    
    all_scores = ALL_SCORES2
    x = 1
    maxi = 0
    for scores in all_scores:
        y = 0
        for base, score in scores:
            gact.letterAt(base, x,y, score, ax)
            y += score
        x += 1
        maxi = max(maxi, y)
    
    plt.xticks(range(1,x))
    plt.xlim((0, x)) 
    plt.ylim((0, maxi)) 
    plt.tight_layout()      
    plt.show()
    

提交回复
热议问题