开发者

Setting range of a colormap in Matplotlib

开发者 https://www.devze.com 2023-04-08 16:00 出处:网络
I\'m using matplotlib to plot a simple graph: cm=plt.get_cmap(\'Blues\') nx.draw_circular(G, node_color=\'White\',

I'm using matplotlib to plot a simple graph:

cm=plt.get_cmap('Blues')

nx.draw_circular(G,
        node_color='White',
        edge_color=range(G.number_of_edges()),
        edge_cmap=cm,
        node_size=900,
        width=4
   开发者_运维技巧     )

I want to set a range on the colormap 'Blues' in such a way to delete the white color which is not visible in the draw.

Please help!

Sorry for bad english.


The range (or normilization) is not really a feature of the colormap, but is often implemented as a feature in the functions that plot using colormaps. For example, imshow uses vmin and vmax, so you might try using these as keywords with draw_circular (I can't find the documentation), or maybe norm.

Other than this, you can make your own colormap with exact color arrangement that you want. There are plenty of examples on how to make custom colormaps, and a few different approaches available. Here (a, b, c, d) are a few examples that might be useful to you.


I ran into this problem trying to plot data with different colormaps:

Setting range of a colormap in Matplotlib

It's hard to which of the whitish dots belong to which distribution. I solved this problem by chopping off the whiter parts of the colormap spectrum:

Setting range of a colormap in Matplotlib

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


def chop_cmap_frac(cmap: LinearSegmentedColormap, frac: float) -> LinearSegmentedColormap:
    """Chops off the beginning `frac` fraction of a colormap."""
    cmap_as_array = cmap(np.arange(256))
    cmap_as_array = cmap_as_array[int(frac * len(cmap_as_array)):]
    return LinearSegmentedColormap.from_list(cmap.name + f"_frac{frac}", cmap_as_array)


cmap1 = plt.get_cmap('Reds')
cmap2 = plt.get_cmap('Blues')

cmap1 = chop_cmap_frac(cmap1, 0.4)
cmap2 = chop_cmap_frac(cmap2, 0.4)
np.random.seed(42)
n = 50
xs = np.random.normal(size=n)
ys = np.random.normal(size=n)
vals = np.random.uniform(size=n)

plt.scatter(xs, ys, c=vals, cmap=cmap1)
plt.scatter(ys, xs, c=vals, cmap=cmap2)
plt.gca().set_facecolor('black')
plt.colorbar()
plt.show()
0

精彩评论

暂无评论...
验证码 换一张
取 消