Matplotlib Half Color Axis

I use matplotlib to create some charts, and I have some difficulties that I need help with.

problem 1) In order to maintain a consistent color scheme, I need to use only half the color axis. There are only positive values, so I want the zero values ​​to be green, the average values ​​to be yellow, and the highest values ​​to red. The color scheme that most closely matches this is gist_rainbow_r, but I want only its upper half.

problem 2) I can’t understand how to get the color bar on the right side of the plot to show or how to get it to give me the axis label.

If this helps, I use the latest version of Anaconda with the later version of matplotlib

cmap = plt.get_cmap('gist_rainbow_r')
edosfig2 = plt.figure(2)
edossub2 = edosfig.add_subplot(1,1,1)
edossub2 = plt.contourf(eVec,kints,smallEDOS,cmap=cmap)
edosfig2.show()
+4
source share
1 answer

If you have a specific set of colors that you want to use for your color map, you can build it based on these. For instance:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

cmap = LinearSegmentedColormap.from_list('name', ['green', 'yellow', 'red'])

# Generate some data similar to yours
y, x = np.mgrid[-200:1900, -300:2000]
z = np.cos(np.hypot(x, y) / 100) + 1

fig, ax = plt.subplots()

cax = ax.contourf(x, y, z, cmap=cmap)
cbar = fig.colorbar(cax)
cbar.set_label('Z-Values')

plt.show()

enter image description here


However, if you just want to get the first half of a particularly complex color map, you can copy part of it by evaluating the color code in the range of interest to you. For example, if you want the "upper" half, you will evaluate it from 0.5 to 1:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# Evaluate an existing colormap from 0.5 (midpoint) to 1 (upper end)
cmap = plt.get_cmap('gist_earth')
colors = cmap(np.linspace(0.5, 1, cmap.N // 2))

# Create a new colormap from those colors
cmap2 = LinearSegmentedColormap.from_list('Upper Half', colors)

y, x = np.mgrid[-200:1900, -300:2000]
z = np.cos(np.hypot(x, y) / 100) + 1

fig, axes = plt.subplots(ncols=2)
for ax, cmap in zip(axes.flat, [cmap, cmap2]):
    cax = ax.imshow(z, cmap=cmap, origin='lower',
                    extent=[x.min(), x.max(), y.min(), y.max()])
    cbar = fig.colorbar(cax, ax=ax, orientation='horizontal')
    cbar.set_label(cmap.name)

plt.show()

enter image description here

+9
source

Source: https://habr.com/ru/post/1548407/


All Articles