在python中高亮显示包含特定点的散点图部分。

问题描述 投票:0回答:1

我试图创建一个曼哈顿图,在给定散点图中各点对应的数值列表的情况下,该图的某些部分将被垂直突出显示。我看了几个例子,但我不知道该如何进行。我想使用 axvspan 或 ax.fill_between 应该可以,但我不确定如何操作。下面的代码是直接从如何用python中的matplotlib创建曼哈顿图?

from pandas import DataFrame
from scipy.stats import uniform
from scipy.stats import randint
import numpy as np
import matplotlib.pyplot as plt

# some sample data
df = DataFrame({'gene' : ['gene-%i' % i for i in np.arange(10000)],
'pvalue' : uniform.rvs(size=10000),
'chromosome' : ['ch-%i' % i for i in randint.rvs(0,12,size=10000)]})

# -log_10(pvalue)
df['minuslog10pvalue'] = -np.log10(df.pvalue)
df.chromosome = df.chromosome.astype('category')
df.chromosome = df.chromosome.cat.set_categories(['ch-%i' % i for i in range(12)], ordered=True)
df = df.sort_values('chromosome')

# How to plot gene vs. -log10(pvalue) and colour it by chromosome?
df['ind'] = range(len(df))
df_grouped = df.groupby(('chromosome'))

fig = plt.figure()
ax = fig.add_subplot(111)
colors = ['red','green','blue', 'yellow']
x_labels = []
x_labels_pos = []
for num, (name, group) in enumerate(df_grouped):
    group.plot(kind='scatter', x='ind', y='minuslog10pvalue',color=colors[num % len(colors)], ax=ax)
    x_labels.append(name)
    x_labels_pos.append((group['ind'].iloc[-1] - (group['ind'].iloc[-1] - group['ind'].iloc[0])/2))
ax.set_xticks(x_labels_pos)
ax.set_xticklabels(x_labels)
ax.set_xlim([0, len(df)])
ax.set_ylim([0, 3.5])
ax.set_xlabel('Chromosome')

给定一个点的值列表,pvalues,例如

lst = [0.288686, 0.242591, 0.095959, 3.291343, 1.526353]

我如何在图中高亮显示包含这些点的区域,就像下图中绿色所示?类似于

Text](https://stackoverflow.com/image.jpg)[![enter image description here]1

python matplotlib
1个回答
0
投票

如果你有一个你的数据框架的样本供你参考,那将会有帮助。

假设你想匹配你的 lst 值与Y值,你需要遍历你要绘制的每个Y值,并检查它们是否在lst内。

for num, (name, group) in enumerate(df_grouped):

组内 你的代码中的变量本质上是你的主数据框架的部分数据帧。df. 因此,你需要在另一个循环中寻找所有的Y值,以满足你的需求。lst 匹配

region_plot = []
for num, (name, group) in enumerate(a.groupby('group')):
    group.plot(kind='scatter', x='ind', y='minuslog10pvalue',color=colors[num % len(colors)], ax=ax)
    #create a new df to get only rows that have matched values with lst
    temp_group = group[group['minuslog10pvalue'].isin(lst)] 
    for x_group in temp_group['ind']:
        #If condition to make sure same region is not highlighted again
        if x_group not in region_plot:
            region_plot.append(x_group)
            ax.axvspan(x_group, x_group+1, alpha=0.5, color='green')
            #I put x_group+1 because I'm not sure how big of a highlight range you want

希望对大家有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.