观看不同颜色的 2D DNA walk

问题描述

我对创建一种形式的 RandomWalk 感兴趣,使用 DNA 序列来创建步行(例如 T = 向上,A = 向下等)。我已经创建了代码,但是我想知道是否可以为 4 个基本字母中的每一个分配一种颜色,而不是最终的绘图图只有一种颜色?

import matplotlib.pyplot as plt 

x = y = 0

x_values = [0]
y_values = [0]

dna_seq =  ('GGACTTCCCTATGGTGCTAACAAAGAGGCAGACAAA')


for base in dna_seq:
    if base == 'T':
        y += 1
    elif base == 'A':
        y -= 1
    elif base == 'G':
        x += 1
    elif base == 'C':
        x -= 1 
    x_values.append(x)
    y_values.append(y)
    
            

fig,ax = plt.subplots()
ax.plot(x_values,y_values,c='g')
plt.show()    

解决方法

您可以使用字典来创建颜色列表。 然后,使用 plt.plot 绘制线条,使用 plt.scatter 绘制彩色点:

您的代码的改编版本:

import matplotlib.pyplot as plt 

x = y = 0

x_values = [0]
y_values = [0]

color_lookup = {'A': 'red','T':'green','G': 'blue','C': 'orange'}


dna_seq =  ('GGACTTCCCTATGGTGCTAACAAAGAGGCAGACAAA')

colors = ['k'] # initialise starting point with black

for base in dna_seq:
    if base == 'T':
        y += 1
    elif base == 'A':
        y -= 1
    elif base == 'G':
        x += 1
    elif base == 'C':
        x -= 1 
    x_values.append(x)
    y_values.append(y)
    colors.append(color_lookup[base])
    
            

fig,ax = plt.subplots()
ax.plot(x_values,y_values,c='k')
ax.scatter(x_values,c=colors)
plt.show()    

enter image description here

,

可以使用基于 this example 的彩色线条。这个想法是将线分成序列,然后使用 LineCollection 绘制线。集合的每一行都可以有自己的颜色。

由于随机游走器多次使用一些段,因此必须稍微移动一些段。

import matplotlib.pyplot as plt 

x = y = 0.
x_values = [0.]
y_values = [0.]
colors = []

dna_seq =  ('GGACTTCCCTATGGTGCTAACAAAGAGGCAGACAAA')#
color_lookup = {'A': 'red','C': 'orange'}

for base in dna_seq:
    if base == 'T':
        y += 1
    elif base == 'A':
        y -= 1
    elif base == 'G':
        x += 1
    elif base == 'C':
        x -= 1 
    x_values.append(x)
    y_values.append(y)
    colors.append(color_lookup[base])

import numpy as np
from matplotlib.collections import LineCollection

points = np.array([x_values,y_values]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]],axis=1)

#handle collisions (algorithm could probably be improved :-) )
delta = 0.1
changed=True
while changed:
    changed=False
    for idx,segment in enumerate(segments):
        if idx > 0:
            cur_seg = segment.tolist()
            if cur_seg in segments[:idx-1].tolist() or [cur_seg[1],cur_seg[0]] in segments[:idx].tolist():
                if(cur_seg[0][0] == cur_seg[1][0]):
                    segment[0][0] += delta
                    segment[1][0] += delta
                else:
                    segment[0][1] += delta
                    segment[1][1] += delta
                changed=True

fig,ax = plt.subplots()
lc = LineCollection(segments,colors=colors)
lc.set_linewidth(2)
ax.add_collection(lc)

ax.set_aspect('equal')
ax.set_xlim(min(x_values)-.1,max(x_values)+.1)
ax.set_ylim(min(y_values)-.1,max(y_values)+.1)

plt.show() 

enter image description here