首页 > 解决方案 > 突出显示包含python中特定点的散点图的一部分

问题描述

我正在尝试创建一个曼哈顿图,该图将在图的某些部分垂直突出显示,给出与散点图中的点相对应的值列表。我看了几个例子,但我不知道如何继续。我认为使用 axvspan 或 ax.fill_between 应该可以,但我不确定如何。下面的代码直接取自 How to create a Manhattan plot with matplotlib in python?

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]

如何在图中突出显示包含这些点的区域,如下图绿色所示?类似于:

文本](https://stackoverflow.com/image.jpg)[![在此处输入图像描述] 1

标签: pythonmatplotlib

解决方案


如果您有一个数据框样本供您参考,这将有所帮助。

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

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

代码中的组变量本质上是主数据框df的部分数据框。因此,您需要放入另一个循环来查看lst匹配的所有 Y 值

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

希望这可以帮助!


推荐阅读