Setting colorbar range on fenics plot

Howdy,

So I added a colorbar to a fenics plot and wanted to know how to actually set the bounds on it such that for example the colorbar goes from -5 to 5 for example. Looking at the output type of the plot fenics function it is <class ‘matplotlib.tri.tricontour.TriContourSet’> . Any thoughts?

from dolfin import *
import pylab as plt
import numpy as np

# Create mesh and define function space
mesh = UnitSquareMesh(32, 32)
V = FunctionSpace(mesh, "Lagrange", 1)

# Define Dirichlet boundary (x = 0 or x = 1)
def boundary(x):
    return x[0] < DOLFIN_EPS or x[0] > 1.0 - DOLFIN_EPS

# Define boundary condition
u0 = Constant(0.0)
bc = DirichletBC(V, u0, boundary)

# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Expression("10*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)",degree=2)
g = Expression("sin(5*x[0])",degree=2)
a = inner(grad(u), grad(v))*dx
L = f*v*dx + g*v*ds

# Compute solution
u = Function(V)
solve(a == L, u, bc)

# Save solution in VTK format
# file = File("poisson.pvd")
# file << u

# Plot solution
c=plot(u)
print(type(c))
# plt.colorbar(c)
# plt.show()
print(dir(c))
plt.colorbar(c)



plt.show()

Hi, plot accepts keywords arguments which are passed to the related matplotlib objects. Consider

from dolfin import *
import pylab as plt
import numpy as np

# Create mesh and define function space
mesh = UnitSquareMesh(32, 32)
V = FunctionSpace(mesh, 'Lagrange', 1)
f = Expression('10*(x[0]+x[1]-1)', degree=1)

c = plot(interpolate(f, V), mode='color')
plt.colorbar(c)

plt.figure()
c = plot(interpolate(f, V), mode='color', vmin=-3, vmax=3)
plt.colorbar(c)

plt.show()
1 Like

Hey MiroK,

Thanks a lot. From your code when you set vmin vmax I would expect the colorbar range to be between -3 to 3. This is what I want. When I run your code it goes from -10 to 10. Do you know how to make the actual color plot axis on an interval? I’m making several plots, and I wanted them to be on the same color bar interval so we can actually say something intellectual.

There should be 2 plots where the second one has the range -3 to 3. This works for me with FEniCS 2017.2.0 from Ubuntu package for 18.04 (matplotlib 2.2.3)

1 Like

Thanks MiroK, I’m a moron. Works great, thank you for pointing this out for me :slight_smile:

I will take the chance of advertising here the use of vtkplotter :slight_smile:

...
from vtkplotter.dolfin import plot

plot(u, mode='color', vmin=-3, vmax=3, style=1)

2 Likes

Nice - I will use this in the future :slight_smile:

1 Like

I couldn’t vtkplotter to work for me, it keeps showing No module found, although I did install using pip

Library name has changed, try:

pip install vedo
1 Like

Yes, thank you, I actually saw that in another of your posts right after I posted this query. Thanks, again.

1 Like