如何在python中为值列表绘制平滑曲线?

2024-06-16 15:06:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为一对多序列比对序列创建了一个香农熵值列表。在绘制值时,我得到了一个简单的绘图。我想在直线上画一条平滑的曲线。有人能告诉我什么是正确的处理方法吗?基本上,我想画一条平滑的曲线,它接触到每一条线的顶端,然后在“y轴值”为零的地方变为零。 图像的链接:[1]:https://i.stack.imgur.com/SY3jH.png

#importing the relevant packages
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.interpolate import make_interp_spline
from Bio import AlignIO
import warnings
warnings.filterwarnings("ignore")

#function to calculate the Shannon Entropy of a MSA
# H = -sum[p(x).log2(px)]

def shannon_entropy(list_input):
    unique_aa = set(list_input)   
    M = len(list_input)
    entropy_list = []
    # Number of residues in column
    for aa in unique_aa:
        n_i = list_input.count(aa)                                           
        P_i = n_i/float(M)                                
        entropy_i = P_i*(math.log(P_i,2))
        entropy_list.append(entropy_i)
    sh_entropy = -(sum(entropy_list))
    #print(sh_entropy)
    return sh_entropy

#importing the MSA file
#importing the clustal file
align_clustal1 =AlignIO.read("/home/clustal.aln", "clustal")

def shannon_entropy_list_msa(alignment_file):
    shannon_entropy_list = []
    for col_no in range(len(list(alignment_file[0]))):
        list_input = list(alignment_file[:, col_no])
        shannon_entropy_list.append(shannon_entropy(list_input))
    return shannon_entropy_list

clustal_omega1 = shannon_entropy_list_msa(align_clustal1)

# Plotting the data
plt.figure(figsize=(18,10))
plt.plot(clustal_omega1, 'r')
plt.xlabel('Residue', fontsize=16)
plt.ylabel("Shannon's entropy", fontsize=16)
plt.show()

编辑1: 下面是实现“pchip”方法后我的图形的外观。pchip输出的链接:https://i.stack.imgur.com/hA3KW.png


Tags: theinimportinputasshpltlist
1条回答
网友
1楼 · 发布于 2024-06-16 15:06:11

pchip monotonic spline output

一种方法是使用PCHIP插值,这将为您提供y轴上零值所需行为的单调曲线

我们无法在我们的计算机上运行您的确切代码示例,因为您指向“home”目录中的本地Clustal文件

下面是一个简单的工作示例,带有指向输出图像的链接:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import pchip


mylist = [10,0,0,0,0,9,9,0,0,0,11,11,11,0,0]
mylist_np = np.array(mylist)
samples = np.array(range(len(mylist)))    
xnew = np.linspace(samples.min(), samples.max(), 100)
plt.plot(xnew,pchip(samples, mylist_np )(xnew))
plt.show() 

plot from code

相关问题 更多 >