0

I'm trying to plot out a contour plot with a colour scheme that has one colour for positive values and one colour for negative values. I tried using the answer in Colorplot that distinguishes between positive and negative values but to no avail. I've attached a snippet of code below, with this code the cmap doesn't separate Red and Blue at 0 but at -40. What exactly is wrong?

import numpy as np
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator

Vr=1438.7228 #some constants
Va=626.8932
dr=3.11
da=1.55

def func(x,y):
    repulsive = Vr*np.log( ((y+x)**2 + dr**2)/((y-x)**2 + dr**2) )
    attractive = Va*np.log( ((y+x)**2 + da**2)/((y-x)**2 + da**2) )
    return (1.0/(4.0*x*y))*(repulsive-attractive)

x = np.linspace(1e-4,10,100) 
y = np.linspace(1e-4,10,100)

X, Y = np.meshgrid(x, y)

Z = func(X,Y)

levels = MaxNLocator(nbins=15).tick_values(Z.min(), Z.max())
cmap = plt.get_cmap('RdBu')
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)

sc = plt.contourf(X, Y, Z, norm=norm, cmap=cmap)
plt.colorbar(sc)
plt.show()

AlphaBetaGamma96
  • 567
  • 3
  • 6
  • 21
  • works pretty well for me. What exactly are you expecting? – Quang Hoang Jun 02 '20 at 15:17
  • Sorry, I should've mentioned that func(x,y) was just a placeholder equation of x*y. I'll re-edit now to contain the function I'm using which doesn't separate out the colours correctly! – AlphaBetaGamma96 Jun 02 '20 at 15:33
  • 1
    `Z_abs_max = max(abs(Z.min()), abs(Z.max()))` and `....tick_values(-Z_abs_max, Z_abs_max)` could work. – JohanC Jun 02 '20 at 15:45
  • @JohanC, that solves the problem! Thank you! Although, I can't seem to increase the number of bins in the colorbar? Would you know how to increase the number of bins as well? – AlphaBetaGamma96 Jun 02 '20 at 15:52
  • 1
    With `plt.contourf(..., levels=levels)`? – JohanC Jun 02 '20 at 15:56

0 Answers0