Rectangle 27 108

From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()

Great example, should be in matplotlib gallery

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

python - matplotlib colorbar for scatter - Stack Overflow

python colors matplotlib
Rectangle 27 107

Using vmin and vmax forces the range for the colors. Here's an example:

import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )

def do_plot(n, f, title):
    #plt.clf()
    plt.subplot(1, 3, n)
    plt.pcolor(X, Y, f(data), cmap=cm, vmin=-4, vmax=4)
    plt.title(title)
    plt.colorbar()

plt.figure()
do_plot(1, lambda x:x, "all")
do_plot(2, lambda x:np.clip(x, -4, 0), "<0")
do_plot(3, lambda x:np.clip(x, 0, 4), ">0")
plt.show()

python - Set Colorbar Range in matplotlib - Stack Overflow

python graph matplotlib
Rectangle 27 7

The solution of using a list of axes by abevieiramota works very well until you use only one row of images, as pointed out in the comments. Using a reasonable aspect ratio for figsize helps, but is still far from perfect. For example:

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9.75, 3))
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

fig.colorbar(im, ax=axes.ravel().tolist())

plt.show()

The colorbar function provides the shrink parameter which is a scaling factor for the size of the colorbar axes. It does require some manual trial and error. For example:

fig.colorbar(im, ax=axes.ravel().tolist(), shrink=0.75)

python - Matplotlib 2 Subplots, 1 Colorbar - Stack Overflow

python matplotlib subplot colorbar
Rectangle 27 3

As pointed out in other answers, the idea is usually to define an axes for the colorbar to reside in. There are various ways of doing so; one that hasn't been mentionned yet would be to directly specify the colorbar axes at subplot creation with plt.subplots(). The advantage is that the axes position does not need to be manually set and in all cases with automatic aspect the colorbar will be exactly the same height as the subplots. Even in many cases where images are used the result will be satisfying as shown below.

When using plt.subplots(), the use of gridspec_kw argument allows to make the colorbar axes much smaller than the other axes.

fig, (ax, ax2, cax) = plt.subplots(ncols=3,figsize=(5.5,3), 
                  gridspec_kw={"width_ratios":[1,1, 0.05]})

This works well, if the plots' aspect is autoscaled or the images are shrunk due to their aspect in the width direction (as in the above). If, however, the images are wider then high, the result would look as follows, which might be undesired.

fix the colorbar height to the subplot height

mpl_toolkits.axes_grid1.inset_locator.InsetPosition
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition

fig, (ax, ax2, cax) = plt.subplots(ncols=3,figsize=(7,3), 
                  gridspec_kw={"width_ratios":[1,1, 0.05]})
fig.subplots_adjust(wspace=0.3)
im  = ax.imshow(np.random.rand(11,16), vmin=0, vmax=1)
im2 = ax2.imshow(np.random.rand(11,16), vmin=0, vmax=1)
ax.set_ylabel("y label")

ip = InsetPosition(ax2, [1.05,0,0.05,1]) 
cax.set_axes_locator(ip)

fig.colorbar(im, cax=cax, ax=[ax,ax2])

plt.show()

python - Matplotlib 2 Subplots, 1 Colorbar - Stack Overflow

python matplotlib subplot colorbar
Rectangle 27 1

plt.clim
cb.patch.set_facecolor((0.2, 0.2, 0.2, 1.0))

awesome, that does the trick. I'm not quite sure why, though.

Honestly I don't really know why either. Apparently they use this patch for the colorbar background rather than the standard axisbg.

Ok, thanks for the explanation. Interestingly, making the patch fully transparent (cb.patch.set_alpha(0)), does not change anything...

Ya, I noticed that too. Presumably @tcaswell would know the answer.

python - Matplotlib: change background color of colorbar (when using t...

python matplotlib
Rectangle 27 0

This is a huge, ugly hack. But no other way would work. Maybe someone else can improve.

fig1 = pylab.figure()
fig2 = pylab.figure()
ax1 = fig1.add_subplot(111)
ax2 = fig2.add_subplot(111)
ax1.scatter(range(10), range(10), c=range(10), alpha=0.2)
im = ax2.scatter(range(10), range(10), c=range(10), alpha=1.0)
fig1.colorbar(im, ax=ax1)
fig1.show()

+1: interesting idea! One drawback is that you get an additional figure when pyplot.show() is called (that could be destroyed, arguably).

Indeed, it creates a new figure. That was really a "last resort" solution. :-)

python - Partially transparent scatter plot, but with a solid color ba...

python matplotlib scatter colorbar
Rectangle 27 0

The out-of-bounds colors can be set using the set_over and set_under methods of the colormap; see the documentation. You'll need to specify these values when you create your colormap. I don't see any matplotlibrc setting to set the default for this, though. You might also want to ask on the matplotlib mailing list.

Edit: I see what is going on. The white area you describe is not beyond the limits of the color range. It is simply the blank background of the axes. Because you are only plotting certain levels, any levels outside that range will not be plotted at all, leaving those areas blank. To get what you want, do this:

cs = pyplot.contourf(x,y,z,levels=np.arange(50, 220, 20), cmap=pyplot.cm.jet, extend="both")
cs.cmap.set_under('k')
cs.set_clim(50, 210)
cb = pyplot.colorbar(cs)

The "extend" argument is the key; it tells contourf to go ahead and plot all contours, but collapse all outside the given range into "too big" and "too small" categories. The cs.set_clim call is necessary to work around an oddity I discovered in contourf while debugging this; for some reason when you use extend, it manipulates the data limits, so we need to reset them back to what we want them to be.

Also, just as a matter of style, you shouldn't be doing things like Colormap.set_under(cmap,color='k'). This is calling the class method and explicitly passing the instance in, which is an odd way to do it. Just do cmap.set_under(color="k").

cs = m.contourf(x,y,data,clevs,cmap=pyplot.cm.Spectral)
cmap=matplotlib.colors.Colormap('Spectral') matplotlib.colors.Colormap.set_under(cmap,color=(0.4667,0,0.5333)) cs = m.contourf(x,y,data,clevs,cmap=cmap)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 943, in _process_colors     self.monochrome = self.cmap.monochrome AttributeError: Colormap instance has no attribute 'monochrome'

You are instantiating the base Colormap class, creating a new, empty Colormap, not using the "spectral" colormap. The easiest way to do what you want is probably to do cmap = pyplot.cm.Spectral and then do cmap.set_under(...). This will modify the Spectral colormap to have the specified under-value. Note that since you are modifying the actual Spectral colormap object, this will remain in effect on all subsequent plots using the Spectral colormap.

That makes sense, but employing this did not change the resulting plot, and the "over/under" color is still white.

It's getting too hard to do this in the abstract. You'll need to provide some example code.

from matplotlib import pyplot as plt from numpy import arange,meshgrid from matplotlib.colors import Colormap  x,y = arange(-10,10),arange(-10,10) x,y=meshgrid(x,y) z = x**2+y**2 clevs=arange(50,220,20) cmap=plt.cm.jet Colormap.set_under(cmap,color='k') cs = plt.contourf(x,y,z,clevs,cmap=cmap) plt.colorbar(cs) plt.show()

Python matplotlib change default color for values exceeding colorbar r...

python matplotlib contour color-mapping colorbar
Rectangle 27 0

It sounds like you want something like a stacked bar chart with the color values mapped to a given range? In that case, here's a rough example:

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

# Generate data....
intervals, weights = [], []
max_weight = 5
for _ in range(30):
    numtimes = np.random.randint(3, 15)
    times = np.random.randint(1, 24*60 - 1, numtimes)
        times = np.r_[0, times, 24*60]
    times.sort()
    intervals.append(np.diff(times) / 60.0)
    weights.append(max_weight * np.random.random(numtimes + 1))

# Plot the data as a stacked bar chart.
for i, (interval, weight) in enumerate(zip(intervals, weights)):
    # We need to calculate where the bottoms of the bars will be.
    bottoms = np.r_[0, np.cumsum(interval[:-1])]

    # We want the left edges to all be the same, but increase with each day.
    left = len(interval) * [i]
    patches = plt.bar(left, interval, bottom=bottoms, align='center')

    # And set the colors of each bar based on the weights
    for val, patch in zip(weight, patches):
        # We need to normalize the "weight" value between 0-1 to feed it into
        # a given colorbar to generate an actual color...
        color = cm.jet(float(val) / max_weight)
        patch.set_facecolor(color)

# Setting the ticks and labels manually...
plt.xticks(range(0, 30, 2), range(1, 31, 2))
plt.yticks(range(0, 24 + 4, 4), 
           ['12am', '4am', '8am', '12pm', '4pm', '8pm', '12am'])
plt.xlabel('Day')
plt.ylabel('Hour')
plt.axis('tight')
plt.show()

matplotlib - creating a color coded time chart using colorbar and colo...

python matplotlib colorbar color-mapping
Rectangle 27 0

plt.clim
cb.patch.set_facecolor((0.2, 0.2, 0.2, 1.0))

awesome, that does the trick. I'm not quite sure why, though.

Honestly I don't really know why either. Apparently they use this patch for the colorbar background rather than the standard axisbg.

Ok, thanks for the explanation. Interestingly, making the patch fully transparent (cb.patch.set_alpha(0)), does not change anything...

Ya, I noticed that too. Presumably @tcaswell would know the answer.

python - Matplotlib: change background color of colorbar (when using t...

python matplotlib
Rectangle 27 0

Also, there is the mincnt option to set the minimum count in hexbin, which leaves all bins with less than this number blank. This makes it very easy to distinguish between zero and one counts in the jet color scheme.

hexbin( ...., mincnt=1)

graph - making small values visible on matplotlib colorbar in python -...

python graph plot matplotlib binning
Rectangle 27 0

Use Matplotlib cm module to map your grayscale to color values. If i remember correctly "jet" is the default colormap. So you would do something like:

uncertainty = plt.cm.jet(data_property.data)
uncertainty[..., 3] = data_uncertainty.data

I tried it, but it still in grayscale. :S

Show "Heat Map" image with alpha values - Matplotlib / Python - Stack ...

python matplotlib rgba colorbar imshow
Rectangle 27 0

This (coloring by a third variable) is what scatter is intended for. You'll need to use it (or a proxy ScalarMappable) to get a colormap.

Because all three of your axes are displaying the same data with the colormap, you don't need to do anything fancy for the colorbar. It's identical between all plots.

As a quick example based on yours:

import numpy as np
import matplotlib.pyplot as plt

time, x, p, q, r = np.random.random((5, 50))

fig, axes = plt.subplots(ncols=3)
for ax, y in zip(axes.flat, [p, q, r]):
    # "s=150" indicates a markersize of 15 points (blame matlab)
    scat = ax.scatter(x, y, c=time, s=150, cmap='jet')
fig.colorbar(scat)

plt.show()

matplotlib - Adding a colorbar to python subplots where color of datap...

python matplotlib colorbar
Rectangle 27 0

#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.

Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""

from pylab import *


delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians

cmap = cm.get_cmap('PiYG', 11)    # 11 discrete colors

im = imshow(Z, cmap=cmap, interpolation='bilinear',
            vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()

show()

which produces the following image:

python - Matplotlib discrete colorbar - Stack Overflow

python matplotlib
Rectangle 27 0

To answer your question about the colorbar axis, the numbers represent

[bottom_left_x_coord, bottom_left_y_coord, width, height]

An appropriate colorbar might be

# x    y    w     h
[0.2, 0.1, 0.6, 0.05]

Here's your code, somewhat reworked which adds a colorbar:

import numpy as np
import matplotlib.pyplot as plt

WIDTH = 9

def uniformity_calc(x):
    return x.mean()

def plotter(x, y, zs, name, units, efficiency=True):
    fig, axarr = plt.subplots(1, 3, figsize=(WIDTH, WIDTH/3), 
                              subplot_kw={'aspect':1})
    fig.suptitle(name)

    UI = map(uniformity_calc, zs)
    ranges = map(lambda x: int(np.max(x)-np.min(x)), zs)

    for ax, z, unif, rangenum in zip(axarr, zs, UI, ranges):
        scat = ax.scatter(x, y, c=z, s=100, cmap='rainbow')
        label = 'Uniformity: %i'%unif
        if not efficiency:
            label += '    %i ppm'%rangenum
        ax.set_xlabel(label)

    # Colorbar [left, bottom, width, height
    cax = fig.add_axes([0.2, 0.1, 0.6, 0.05])
    cbar = fig.colorbar(scat, cax, orientation='horizontal')
    cbar.set_label('This is a colorbar')
    plt.show()


def main():
    x, y = np.meshgrid(np.arange(10), np.arange(10))
    zs = [np.random.rand(*y.shape) for _ in range(3)]
    plotter(x.flatten(), y.flatten(), zs, 'name', None)

if __name__ == "__main__":
    main()

python - Matplotlib - 2 problems. Common colorbar / labels not showing...

python matplotlib plot
Rectangle 27 0

quiver
clim
fig = plt.quiver(x, y, vector_field_x, vector_field_y, m, clim=[-2,2])

Hi, @Falko. I'm having the exactly same problem with contour. I tried to use clim, unsuccessful. Do you know a solution for this case? Thank you.

python - How to set a color bar range in Matplotlib? - Stack Overflow

python matplotlib range colorbar
Rectangle 27 0

There are multiple ways, but the simplest is just to specify the vmin and vmax kwargs to imshow. Alternately, you can make a matplotlib.cm.Colormap instance and specify it, but that's more complicated than necessary for simple cases.

Here's a quick example with a single colorbar for all images:

import numpy as np
import matplotlib.pyplot as plt

# Generate some data that where each slice has a different range
# (The overall range is from 0 to 2)
data = np.random.random((4,10,10))
data *= np.array([0.5, 1.0, 1.5, 2.0])[:,None,None]

# Plot each slice as an independent subplot
fig, axes = plt.subplots(nrows=2, ncols=2)
for dat, ax in zip(data, axes.flat):
    # The vmin and vmax arguments specify the color limits
    im = ax.imshow(dat, vmin=0, vmax=2)

# Make an axis for the colorbar on the right side
cax = fig.add_axes([0.9, 0.1, 0.03, 0.8])
fig.colorbar(im, cax=cax)

plt.show()

matplotlib - How can I create a standard colorbar for a series of plot...

python matplotlib colorbar
Rectangle 27 0

If you want to have something similar to the imshow example you linked to but with different coordinate axes, you may want to use the extent keyword of imshow:

import numpy as np
import matplotlib.pyplot as plt

# some random data (10x10)
image = np.random.uniform(size=(10, 10))

plt.figure()

# draw the pixel image
#   interpolation='nearest': draw blocky pixels, do not smooth
#   cmap=pl.cm.gray: use gray scale colormap (autoscale, no vmin or vmax defined
#   origin='lower': draw first row of the array to the bottom if the image
#   extent=[-3,3,-10,10]: draw the image so that it covers area (-3,-10)..(3,10)
plt.imshow(image, cmap=plt.cm.gray, interpolation='nearest', origin='lower', extent=[-3,3,-10,10])

# this is needed to make the pixels non-square if needed
plt.axis('normal')

plt.colorbar()

plt.show()

This way you can create "pixels" whose size is exactly what you want:

Of course, you may plot more information onto the same plot if you want just by using plot or something else.

The image here is an array of scalars and the colouring is defined by the cmap, but it may also be an array of RGB or RGBA values if you want to do fancier coloring. For example:

If you want to have transparent areas in your map, put nan values into image.

Almost got what I needed.. But now, the y axis is shrunken. How to elongate it? I mean x varies from 4 to 22. And y varies from -75 to -70.5. So the prob is it looks like a rectangle with the figure having squeezed along vertical axis, i.e. y axis.

@MycrofD: The extent keyword gives the size of the image in the plot area coordinates. Remember to give the plt.axis('normal') and then you can scale the axis ranges to be what you want by plt.axis([-100,100,-50,50]) or whatever range you want to have.

thank you very much. Thnx to you and @Lev Levitsky for such a quick response. :)

I was using cbar.ax.set_ylabel('something'). It is not working. I can't label the colorbar. Help plz..

@MycrofD: Are you sure you want to set the Y label for the colorbar? That works well with ax.set_ylabel. But if you want to set the Y axis tick labels manually, you need get_yticks().to_list(), edit the list and set_yticklabels. The process has several kinks, see: stackoverflow.com/questions/11244514/

python - Matplotlib, 3rd set of values as colors of colorbar - Stack O...

python matplotlib
Rectangle 27 0

Actually, the solution is so easy it is a bit embarrassing to write it here... Sorry bothering the community!

levels = [-40,-30,-20,-15,-12,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]
# define the colormap
cmap = cm.get_cmap('gist_rainbow_r',52)
# define the bins and normalize
norm = mpl.colors.BoundaryNorm(levels, cmap.N)
contourplot = map.contourf(xpoints,ypoints,fieldtoplot,range(-40,36),cmap=cmap,norm=norm,spacing='uniform', levels=levels)

ax = plt.gca()  # Gets the current axes
divider = make_axes_locatable(ax)  # Lets us move axes around
cax = divider.append_axes("bottom", size="2%",pad=-0.02,axes_class=maxes.Axes)  #Adds an axis for the colorbar
F.add_axes(cax)  # Adds the new axis to the figure as the current working axis
bar = plt.colorbar(contourplot,cax=cax,orientation='horizontal',spacing='uniform',extend='both',extendfrac='auto',extendrect='True',format='%1i',ticks=levels, boundaries=levels) # Plots colorbar in new axis 
bar.update_ticks()

So, to be clear: Set "spacing" to "uniform" (and not equal - by looking at colorbar.py I noticed that this setting did not exist at all) and pass "levels" to the contourf function.

At this point: Thanks @Saullo Castro for partly answering the question!

python - matplotlib: Unequally spaced ticks / Zero at a specific color...

python matplotlib plot colorbar
Rectangle 27 0

I could be very wrong, but you may be able to enforce the right one by passing im into colorbar() as the mappable. In plot2d:

cb = colorbar(im, ax=ax, orientation='vertical')

I think that way it specifies not only the axes but the mappable input. FYI, it makes no difference to me (using 1.3.1) so nothing breaks, but it also means I can't test it.

Thanks, this works in matplotlib 1.1.1

python - Matplotlib wrong colorbar assigned to subplot - Stack Overflo...

python matplotlib plot colorbar
Rectangle 27 0

You are suffering from an off-by-one error. You have 10 ticklabels spread among 11 colors. You might be able to correct the error by using np.linspace instead of np.arange. Using np.linspace the third argument is the number of values desired. This reduces the amount of mental gymnastics needed to avoid the off-by-one error:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.colors as mcolors

def colorbar_index(ncolors, cmap):
    cmap = cmap_discretize(cmap, ncolors)
    mappable = cm.ScalarMappable(cmap=cmap)
    mappable.set_array([])
    mappable.set_clim(-0.5, ncolors+0.5)
    colorbar = plt.colorbar(mappable)
    colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
    colorbar.set_ticklabels(range(ncolors))

def cmap_discretize(cmap, N):
    """Return a discrete colormap from the continuous colormap cmap.

        cmap: colormap instance, eg. cm.jet. 
        N: number of colors.

    Example
        x = resize(arange(100), (5,100))
        djet = cmap_discretize(cm.jet, 5)
        imshow(x, cmap=djet)
    """

    if type(cmap) == str:
        cmap = plt.get_cmap(cmap)
    colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
    colors_rgba = cmap(colors_i)
    indices = np.linspace(0, 1., N+1)
    cdict = {}
    for ki,key in enumerate(('red','green','blue')):
        cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
                       for i in xrange(N+1) ]
    # Return colormap object.
    return mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

fig, ax = plt.subplots()
A = np.random.random((10,10))*10
cmap = plt.get_cmap('YlGnBu')
ax.imshow(A, interpolation='nearest', cmap=cmap)
colorbar_index(ncolors=11, cmap=cmap)    
plt.show()

Hah, I absolutely am suffering from an off-by-one error. Blast.

python - Correcting matplotlib colorbar ticks - Stack Overflow

python matplotlib color-mapping