简体   繁体   中英

change color for first level of contourf

I'm using this script to plot a Ramachandran plot (the kind of plot is not really relevant here, what matters is the outputted graph):

#!/usr/bin/python
# coding: utf-8

"""
Script to plot a heat map of the dihedral angles
http://stackoverflow.com/questions/26351621/turn-hist2d-output-into-contours-in-matplotlib
"""

import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

# print(sys.argv[1])

frame, x, y = np.loadtxt(sys.argv[1], unpack=True)

fig = plt.figure(1)
ax = plt.subplot(111)


counts, ybins, xbins, image = plt.hist2d(x, y, bins=180, norm=LogNorm())
plt.clf()
plt.contourf(counts.transpose(), 10, extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()])

plt.colorbar()

fig.set_size_inches(30, 20)
plt.savefig(sys.argv[1], bbox_inches='tight')

And here is what I obtain:

最终图

That's almost what I want. I would like the first level (0-15 on the color bar), which appears in the darkest purple, to appears white on the graph.

Can it be done ?

Will a mask work, with everything below 15 in white?

from numpy import ma
counts_masked = ma.masked_where(counts<15, counts)
plt.contourf(counts_masked.transpose(), 10, extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()])

Or, another option might be:

levels = np.linspace(15,165,10) # your colorbar range, starting at 15
cmap = plt.get_cmap()
cmap.set_under(color='white')
plt.contourf(counts.transpose(), levels=levels, cmap=cmap, extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()])

I actually found the answer an hour ago, based on this question: Python matplotlib change default color for values exceeding colorbar range

I just wanted to do the opposite, so I set the low limit with the following code:

cs = plt.contourf(counts.transpose(), 10, extent=[xbins.min(), xbins.max(),
                                                  ybins.min(), ybins.max()])

# All bims under 15 are plotted white
cs.cmap.set_under('w')
cs.set_clim(15)

cbar = plt.colorbar(cs)

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