简体   繁体   中英

Custom pcolor in matplotlib

I am plotting several heatmaps in matplotlib as shown below.

在此输入图像描述

Here is my loop:

with open(gene_peak) as f:
    count = 1
    for line in f:
        np_array=[]
        gene_peak = line.strip().split("\t")
        gene_id = gene_peak[0]
        peaks = gene_peak[1].split(",")
        for peak in peaks:
            np_array.append(enhancer_fc[peak])
        data, pval = stats.spearmanr(np.transpose(np.array(np_array)))
        plt.subplot(4,3,count+1)
#       plt.title(gene_id)
        plt.pcolor(data, cmap=plt.cm.OrRd, vmin=-1, vmax=1)
        plt.gca().invert_yaxis()
        plt.gca().set_aspect(aspect='equal', adjustable='box-forced')
        plt.xticks([])
        plt.yticks([])
        print count
        count += 1
    plt.show()

I am plotting the spearman correlations of different 2D arrays of different dimensions.

Question:

There are correlation values, so they range from -1 to 1. I want to add custom colorbar() such that values above 0.4 starts showing a gradient of red and below -0.4 shows a gradient of blue, such that I show only the points that are more than 0.4 and less than -0.4.

在此输入图像描述

Also I would like to plot only one colorbar() such that the image looks cleaner. Any help would be appreciated, Thanks.

You can define your own discrete colormap using the ListedColorMap from Matplotlib. You can use the colorbar from one of the plots, and place it in position so it represent all of the plots visually. Here is an example with the colours you have given:

from matplotlib import colors


discrete_colors = [(255, 0, 20), (255, 70, 65), (255, 128, 110), (255, 181, 165), (64, 64, 64),
    (0, 0, 0), (64, 64, 64), (124, 128, 217), (102, 107, 216), (69, 76, 215), (33, 33, 245)]
discrete_colors = [(r/255., g/255., b/255.) for r, g, b in discrete_colors]         

my_colormap = colors.ListedColormap(discrete_colors)

subplot(211)
data = 2 * np.random.rand(10, 10) - 1.0
pcolor(data, cmap=my_colormap, vmin=-1, vmax=1)
subplot(212)  # Some other plot
data = 2 * np.random.rand(10, 10) - 1.0
pc = pcolor(data, cmap=my_colormap, vmin=-1, vmax=1)

fig = gcf()
fig.subplots_adjust(right=0.70)
cax = fig.add_axes([0.80, 0.15, 0.05, 0.7])
fig.colorbar(pc, cax=cax)

You might have to adjust the code a bit. I'm using IPython 2.7. 自定义离散色彩图和色条位置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM