Skip to content

Graphics

graphics

This module provides a forked version of the 'snipit' method from the 'snipit' repository. The 'snipit' method is used for generating graphical visualizations.

Contents
  • plot_graphic: Plot graphical visualization of variations and k-mer frequencies.

message = Messages() module-attribute

Set the Message class for logging.

plot_graphic(variations, reference_path, freq_kmers, sequence_name, save_path, colour_palette='classic')

Plot graphical visualization of variations and k-mer frequencies.

This function generates a graphical visualization of variations and k-mer frequencies based on the provided inputs. The plot is saved to the specified save path.

Parameters:

Name Type Description Default
variations list

A list of variations to be plotted.

required
ref_sequence str

The reference sequence for comparison.

required
freq_kmers defaultdict[int]

A defaultdict containing k-mer frequencies.

required
sequence_name str

The name of the sequence being analyzed.

required
save_path str

The path to save the generated plot.

required
colour_palette str

The colour palette to use for the plot. Default is 'classic'.

'classic'

Returns:

Type Description
None

Message class: A message confirming the plot was saved.

Source code in python/gramep/graphics.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def plot_graphic(
    variations: list[str],
    reference_path: str,
    freq_kmers: defaultdict[int],
    sequence_name: str,
    save_path: str,
    colour_palette: str = 'classic',
) -> None:
    """
    Plot graphical visualization of variations and k-mer frequencies.

    This function generates a graphical visualization of variations and \
    k-mer frequencies
    based on the provided inputs. The plot is saved to the specified save path.

    Args:
        variations (list): A list of variations to be plotted.
        ref_sequence (str): The reference sequence for comparison.
        freq_kmers (defaultdict[int]): A defaultdict containing k-mer frequencies.
        sequence_name (str): The name of the sequence being analyzed.
        save_path (str): The path to save the generated plot.
        colour_palette (str, optional): The colour palette to use for the plot. \
        Default is 'classic'.

    Returns:
        Message class: A message confirming the plot was saved.
    """
    sorted_variations = []
    y_level = 0
    snp_dict = defaultdict(list)
    ref_vars = {}
    length = ref_length(reference_path)
    colour_dict = get_colours(colour_palette)

    for var in variations:
        pos, variation = var.split(':')
        freq = freq_kmers[var]
        sorted_variations.append((int(pos), variation, freq))
    sorted_variations.sort()

    for variation in sorted_variations:
        y_level += 1
        pos, var, freq = variation
        x_position = pos
        ref = var[0]
        base = var[1]
        ref_vars[x_position] = ref
        snp_dict[x_position].append(
            (
                str('Mutation' + str(y_level) + '\n' + str(freq)),
                ref,
                base,
                y_level,
            )
        )

    spacing = length / (len(snp_dict) + 1)
    y_inc = (spacing * 0.8 * y_level) / length

    # if len(snp_dict) <10:
    #     width = 10
    # else:
    #     width = 0.25* len(snp_dict)

    if y_level < 5:
        height = 5
    else:
        height = y_inc * 3 + 0.5 * y_level + y_inc * 2

    width = height + (height * 0.5)

    # width and height of the figure
    fig, ax = plt.subplots(1, 1, figsize=(width, height), dpi=300)

    y_level = 0
    for snp in snp_dict:
        for sequence in snp_dict[snp]:
            mutation_name, _, _, _ = sequence
            y_level += y_inc

            # either grey or white
            col = next_colour()

            # for each record (sequence) draw a rectangle the length of the whole \
            # genome (either grey or white)
            rect = patches.Rectangle(
                (0, y_level - (0.5 * y_inc)),
                length,
                y_inc,
                alpha=0.3,
                fill=True,
                edgecolor='none',
                facecolor=col,
            )
            ax.add_patch(rect)

            # for each record add the name to the left hand side
            ax.text(
                -50, y_level, mutation_name, size=9, ha='right', va='center'
            )

    position = 0
    for snp in sorted(snp_dict):
        position += spacing

        # write text adjacent to the SNPs shown with the numeric position
        # the text alignment is toggled right/left (top/bottom considering \
        # 90-deg rotation) if the plot is flipped
        ax.text(
            position,
            y_level + (0.55 * y_inc),
            snp,
            size=9,
            ha='center',
            va='bottom',
            rotation=90,
        )

        # snp position labels
        left_of_box = position - (0.4 * spacing)
        right_of_box = position + (0.4 * spacing)

        top_polygon = y_inc * -0.7
        bottom_polygon = y_inc * -1.7

        for sequence in snp_dict[snp]:

            name, ref, var, y_pos = sequence
            bottom_of_box = (y_pos * y_inc) - (0.5 * y_inc)
            # draw box for snp
            # if recombi_out:
            #     rect = patches.Rectangle((left_of_box,bottom_of_box),\
            # spacing*0.8,  y_inc,alpha=0.5, fill=True, \
            # edgecolor='none',facecolor=colour_dict[recombi_out])
            if var in colour_dict:
                rect = patches.Rectangle(
                    (left_of_box, bottom_of_box),
                    spacing * 0.8,
                    y_inc,
                    alpha=0.5,
                    fill=True,
                    edgecolor='none',
                    facecolor=colour_dict[var.upper()],
                )
            else:
                rect = patches.Rectangle(
                    (left_of_box, bottom_of_box),
                    spacing * 0.8,
                    y_inc,
                    alpha=0.5,
                    fill=True,
                    edgecolor='none',
                    facecolor='dimgrey',
                )

            ax.add_patch(rect)

            # sequence variant text
            ax.text(
                position, y_pos * y_inc, var, size=9, ha='center', va='center'
            )

        # reference variant text

        ax.text(position, y_inc * -0.2, ref, size=9, ha='center', va='center')

        # polygon showing mapping from genome to spaced out snps
        x = [snp - 0.5, snp + 0.5, right_of_box, left_of_box, snp - 0.5]

        y = [
            bottom_polygon,
            bottom_polygon,
            top_polygon,
            top_polygon,
            bottom_polygon,
        ]
        coords = list(zip(x, y))

        # draw polygon
        poly = patches.Polygon(
            coords, alpha=0.2, fill=True, edgecolor='none', facecolor='dimgrey'
        )
        ax.add_patch(poly)

        rect = patches.Rectangle(
            (left_of_box, top_polygon),
            spacing * 0.8,
            y_inc,
            alpha=0.1,
            fill=True,
            edgecolor='none',
            facecolor='dimgrey',
        )
        ax.add_patch(rect)

    if len(snp_dict) == 0:
        # snp position labels
        left_of_box = position - (0.4 * position)
        right_of_box = position + (0.4 * position)

        top_polygon = y_inc * -0.7
        bottom_polygon = y_inc * -1.7

    # reference variant rectangle
    rect = patches.Rectangle(
        (0, (top_polygon)),
        length,
        y_inc,
        alpha=0.2,
        fill=True,
        edgecolor='none',
        facecolor='dimgrey',
    )
    ax.add_patch(rect)

    ax.text(-20, y_inc * -0.2, 'Reference', size=9, ha='right', va='center')

    ref_genome_position = y_inc * -2.7

    # reference genome rectangle
    rect = patches.Rectangle(
        (0, ref_genome_position),
        length,
        y_inc,
        alpha=0.2,
        fill=True,
        edgecolor='none',
        facecolor='dimgrey',
    )
    ax.add_patch(rect)

    for var in ref_vars:
        ax.plot(
            [var, var],
            [ref_genome_position, ref_genome_position + (y_inc * 0.98)],
            color='#cbaca4',
        )

    ax.spines['top'].set_visible(False)   ## make axes invisible
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)

    plt.yticks([])

    ax.set_xlim(0, length)
    ax.set_ylim(ref_genome_position, y_level + (y_inc * 1.05))

    seq_name = sequence_name.split('/')[-1].split('.')[0]

    ax.tick_params(axis='x', labelsize=8)
    plt.xlabel('Genome position (base)', fontsize=9)
    plt.title(str(str(seq_name) + ' Mutations'), loc='left')
    plt.tight_layout()

    outputDir = save_path + '/' + seq_name + '/results.pdf'
    plt.savefig(outputDir)

    plt.close()

    return message.info_graphic_saved(str(save_path + '/' + seq_name))