I have plotted some data using matplotlib's imshow. I have also managed to combine three different colormaps for the plot (see figure), but I want the greens to go from 0-1000, the yellow/orange to go from 1000-1600 and reds from 1600 and up. It's almost correct out of the box, but not entirely. Anyone know how I can accomplish this?
colors1 = plt.cm.Greens_r(np.linspace(0, 0.4, 256))
colors2 = plt.cm.Oranges(np.linspace(0.1, 0.5, 256))
colors3 = plt.cm.Reds(np.linspace(0.6, 1, 256))
cmap = np.vstack((colors1, colors2, colors3))
cmap_test = colors.LinearSegmentedColormap.from_list('colormap', cmap)
fig, ax = plt.subplots()
plt.imshow(z, origin='upper', cmap=cmap_test, interpolation='none', extent=[0,25,5,-20])
cbar = plt.colorbar()
ax.grid(linestyle='-')
plt.show()
Related
I working with some satellite images. After I extract the data and convert them in arrays, I use matplotlib's ax.pcolor() to visualize, and got this after using plt.axis('equal')
How can I fit the figure axes to the data automatically? I can do it manually adjusting the axes dimensions. Is there a better way to do that?
src = rasterio.open('imagem_teste.tif')
red = src.read(1)
fig = plt.figure()
ax = fig.add_axes([.1, .1, .465, .8])
ax.pcolor(lon_mtx, lat_mtx, red, cmap = 'jet', shading='auto')
plt.axis('equal')
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
I am using the following code to contour plot some data using contourf in matplotlib. I have set the transparency of the colourbar to 0.6, but there are annoying lines between each colour interval that I cant get rid of. There doesnt seem to be a way to set linestyle in contourf, any ideas?
#instantiating and titiling the figure
fig, ax1 = plt.subplots(figsize=(7,5))
fig.suptitle('Testing Simple Neural Networks', y=0.96, fontsize=16, fontweight='bold');
#defining colour tables
cm = plt.cm.coolwarm
#plotting the contour plot
levels = np.linspace(0, 1, 25)
cont1 = ax1.contourf(p1_mesh, p2_mesh, y_mesh, levels=levels, cmap=cm, alpha=0.6, linewidths=10)
#plotting the entire dataset - training and test data.
scat1 = ax1.scatter(X['p1'],
X['p2'],
c=y,
cmap=cm,
edgecolors='k');
#setting axis and legend
ax1.set(ylabel='p2',
xlabel='p1',
xlim=(0,255),
ylim=(0,255));
ax1.legend(*scat1.legend_elements(), title='Target');
ax1.set_axisbelow(True)
ax1.grid(color='xkcd:light grey')
cbar = fig.colorbar(cont1)
You can add the option antialiased=True to ax1.contourf, it should fix it.
I am trying to add a custom colorbar to my matplotlib figure, that runs from full transparent (white) to full color (mediumpurple).
I have come far, but still a few issues. The way I make this, creates lines between each patch, which are visible. This creates artifacts when I try to make the colorbar look fluent.
fig, ax = plt.subplots(figsize=(10, 10))
max_val = 4
transparency_ticks = 500
color = mpl.colors.to_rgba(color)
cmap = mpl.colors.ListedColormap([(*color[:3], (1+a)/transparency_ticks) for a in range(transparency_ticks)])
norm = mpl.colors.Normalize(vmin=0, vmax=max_val)
cax = fig.add_axes([0.8, 0.17, 0.05, 0.5])
mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, orientation='vertical')
This is the image for transparency_ticks = 500. So you can see the lines between each patch.
This is the image for transparency_ticks = 5000. You don't see the lines anymore since they have blended with the rest, but these lines make the colorbar look a lot darker.
Instead of levels onRGBA, use HSV with various saturation:
fig, ax = plt.subplots(figsize=(10, 10))
max_val = 4
transparency_ticks = 50
colors = [mpl.colors.hsv_to_rgb((0.83, a/transparency_ticks, 1))
for a in range(transparency_ticks)]
cmap = mpl.colors.ListedColormap(colors)
norm = mpl.colors.Normalize(vmin=0, vmax=max_val)
cax = fig.add_axes([0.8, 0.17, 0.05, 0.5])
mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, orientation='vertical')
I am having issues with a plot that I have created where I am getting an unwanted additional color palette on the plot.
My script uses to list of data to create a plot with colored points.
plt.close('all')
fig, axes = plt.subplots(nrows = 1, ncols = 1)
fig.set_facecolor('white')
axes.set_ylabel('$dz$ [$\AA$]')
axes.set_xlabel('Time [ns]')
axes.spines['right'].set_visible(False)
axes.spines['top'].set_visible(False)
axes.yaxis.set_ticks_position('left')
axes.xaxis.set_ticks_position('bottom')
axes.tick_params(direction='out')
#axes.set_title('N/A')
axes.set_ylim(-20,10)
axes.set_xlim(0, 90)
cmap = plt.get_cmap('plasma')
colors = [cmap(i) for i in np.linspace(0, 1, 9)]
# Make Color Bar ------------------------------------------------------
cax = 0
divider = make_axes_locatable(axes)
cax = divider.append_axes('right', size='5%', pad=0.1)
im = axes.imshow(np.linspace(1, 8.5, 100).reshape(10, 10), cmap='plasma')
fig.colorbar(im, cax=cax)
#----------------------------------------------------------------------
for i, dist in enumerate(dz):
if i % 100 == 0:
x = i / 1000
y = dist
phval = final_pH_array[i]
axes.plot(x, y, 'k.', markersize = 4 , color = colors[int(phval)], clip_on = False)
plt.savefig('plot.pdf')
plt.show()
The results looks like this:
As you can see there is an additional color bar / color palette that I don't want on the plot but can't seem to get rid of it.
Any help with this would be great!
I think im.set_visible(False) should achieve what you want.
But maybe you should take a look at plt.scatter. scatter returns a PathCollection that you can pass to the colorbar function.
I have a plot in which I merge two datas. Given that, I have to show two different color bars, one for each data. I'm currently plotting my datas as follows:
plt.figure()
# Data 1
fig = plt.imshow(data1, interpolation='nearest', cmap='binary', vmin=0, vmax=1)
# Plotting just the nonzero values of data2
data2_x = numpy.nonzero(data2)[0]
data2_y = numpy.nonzero(data2)[1]
pts = plt.scatter(data2_x, data2_y, marker='s', c=data2[data2_x, data2_y])
plt.colorbar(pts)
plt.colorbar(fig, orientation="horizontal")
And this is the plot that I get:
However, I would like to reposition the color bars to have something like this (made with Photoshop):
Is that possible?
Thank you in advance.
Probably the 'easiest' way to do this is to lay the axes to be used for the color bars out by hand (via cbax = fig.add_axes([....])). You can then pass that axes to the color bar calls:
Something like:
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure(figsize=(8, 8))
ax = fig.add_axes([.1, .1, .8, .8])
im = ax.imshow(np.random.rand(150, 150), cmap='gray', interpolation='none')
sc = ax.scatter(2 + 146 * np.random.rand(150), 2 + 146 * np.random.rand(150),
c=np.random.rand(150), cmap='Accent', s=50, lw=0)
ax_cb1 = fig.add_axes([.1, .05, .8, .02])
ax_cb2 = fig.add_axes([.92, .1, .02, .8])
cb1 = fig.colorbar(im, cax=ax_cb1, orientation='horizontal')
cb1.ax.xaxis.set_label_position('top')
cb2 = fig.colorbar(sc, cax=ax_cb2, orientation='vertical')
you can link the colorbar to the axes with the ax-keyword, plt.gca() gives you the current axes:
plt.colorbar(object1, ax=plt.gca())