Search code examples
matplotlibplotcolorbarshort

how can i delete the short lines of the colorbar in matplotlib


I've plotting with matplotlib and I have short lines in colorbar :

enter image description here

How can I delete the short lines to have a colorbar like this picture:

enter image description here

What I need to change in my code? My code is here:

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

from __future__ import unicode_literals
from matplotlib import rc
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import matplotlib as cm

phi = open("file1.txt").read().splitlines()
psi = open("file2.txt").read().splitlines()

# normal distribution center at x=0 and y=5
x = np.array(phi).astype(np.float)
y = np.array(psi).astype(np.float)

plt.hist2d(x, y, bins=400, cmap='bone', norm=LogNorm())
plt.colorbar()
plt.title('Distribution')
plt.xlabel(r' Phi ($\phi$)', fontsize=15)
plt.ylabel(r'Psi ($\psi$)', fontsize=15)
plt.rc('xtick', labelsize=11)
plt.rc('ytick', labelsize=11)
plt.xlim((-180,180))
plt.ylim((-180,180))
plt.axhline(0, color='black')
plt.axvline(0, color='black')
plt.grid()
plt.show()

Solution

  • I presume you mean you want to remove the minor ticks from the colorbar.

    You can do this by setting the location of the ticks using a LogLocator from the matplotlib.ticker module. By default, this does not have any minor ticks (i.e. no ticks between the integer powers of the base), so we can use the LogLocator with no other options required.

    You just need to keep a reference to the colorbar as you make it (here I call it cb), then you can use the set_ticks() method on that. Make sure you also set update_ticks=True to make this update the ticks before making the plot.

    (I used some fake data, but otherwise didn't change anything else in your script):

    import matplotlib.ticker as ticker
    
    ...
    
    cb = plt.colorbar()
    cb.set_ticks(ticker.LogLocator(), update_ticks=True)
    
    ...
    

    enter image description here