Make plt.colorbar by following the steps before and after vmin / vmax

I want to do something with plt.hist2dand plt.colorbar, and I am having real problems with how to do this. To explain, I wrote the following example:

import numpy as np
from matplotlib import pyplot as plt

x = np.random.random(1e6)
y = np.random.random(1e6)

plt.hist2d(x, y)
plt.colorbar()

plt.show()

This code generates a graph that looks something like the image below. 2D bar chart with pyplot-colored panel

If I create a histogram, ideally I would like the color bar to go beyond the maximum and minimum data range to the next step beyond the maximum and minimum. In the example in this question, this would set the color bar size from 9660 to 10260 in increments of 60.

How can I force either plt.hist2dor plt.colorbarset the color bar so that the ticks are assigned to the beginning and end of the constructed color bar?

+4
2

, , :

h = plt.hist2d(x, y)
mn, mx = h[-1].get_clim()
mn = 60 * np.floor(mn / 60.)
mx = 60 * np.ceil(mx / 60.)
h[-1].set_clim(mn, mx)
cbar = plt.colorbar(h[-1], ticks=np.arange(mn, mx + 1, 60), )

-

enter image description here

matplotlib.ticker tick_values, , .

!

+3

farenorth, , get_colour_bar_ticks:

def get_colour_bar_ticks(colourbar):
    import numpy as np

    # Get the limits and the extent of the colour bar.
    limits = colourbar.get_clim()
    extent = limits[1] - limits[0]

    # Get the yticks of the colour bar as values (ax.get_yticks() returns them as fractions).
    fractions = colourbar.ax.get_yticks()
    yticks = (fractions * extent) + limits[0]
    increment = yticks[1] - yticks[0]

    # Generate the expanded ticks.
    if (fractions[0] == 0) & (fractions[-1] == 1):
        return yticks

    else:
        start = yticks[0] - increment
        end = yticks[-1] + increment

        if fractions[0] == 0:
            newticks = np.concatenate((yticks, [end]))
        elif fractions[1] == 1:
            newticks = np.concatenate(([start], yticks))
        else:
            newticks = np.concatenate(([start], yticks, [end]))

        return newticks

:

from matplotlib import pyplot as plt

x = np.random.random(1e6)
y = np.random.random(1e6)

h = plt.hist2d(x, y)
cbar = plt.colorbar()

ticks = get_colour_bar_ticks(cbar)

h[3].set_clim(ticks[0], ticks[-1])
cbar.set_clim(ticks[0], ticks[-1])
cbar.set_ticks(ticks)

plt.show()

, :

enter image description here

+2

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


All Articles