matplotlib 在python中修改图形颜色条的值范围

jjjwad0x  于 2022-12-04  发布在  Python
关注(0)|答案(1)|浏览(189)

I have the following issue.
I have a graph of which has colored segments. The problem is in relating those segments to the color bar (which also contains text), so that each color segment is aligned with the color bar.
The code is the following:

from matplotlib.colorbar import colorbar_factory

x_v = datosg["Hour"]+div
y_v = datosg["UV Index"]

fig, ax= plt.subplots(figsize = (7,7))

ax.plot(x_v, y_v, color = "green")
ax.set_xlim(7, 19)
ax.grid()
ax.axhspan(0, 2.5, facecolor='green', alpha=0.8)
ax.axhspan(2.5, 5.5, facecolor='blue', alpha=0.7)
ax.axhspan(5.5, 7.5, facecolor='red', alpha=0.7)
ax.axhspan(7.5, 10.5, facecolor='yellow', alpha=0.7)
ax.axhspan(10.5, 16, facecolor='pink', alpha=0.7)
ax.margins(0)

from matplotlib.colors import ListedColormap

#discrete color scheme

cMap = ListedColormap(['green', 'blue','red', 'yellow', 'pink'])

#data
np.random.seed(42)
data = np.random.rand(5, 5)
heatmap = ax.pcolor(data, cmap=cMap)

#legend

cbar_ay = fig.add_axes([0.93, 0.125, 0.2, 0.755])
cbar = plt.colorbar(heatmap, cax=cbar_ay, orientation="vertical")

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$Bajo$','$Medio$','$Alto$','$Muy Alto$','$Extremo$']):
    cbar.ax.text(.5, (2 * j + 1) / 10.0, lab, ha='center', va='center')

plt.show()

The graph that results from this code is as follows: Result_code
I have tried everything, the result I expect is very similar to this graph: resulting image
But I can't change the range of the colors in the color bar.
Also note that I created random values ​​in order to create the colorbar, I couldn't think of any other way, however so far it has worked. I only have to modify the range, so that it is similar to the last graph.
Any help would be appreciated.

tquggr8v

tquggr8v1#

我想绘制第二个轴并用axhspan填充它要容易得多,就像绘制主轴一样,但是如果你想使用颜色条,你可以如下所示:

import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

colors = ['green', 'blue','red', 'yellow', 'pink']
labels = ['$Bajo$','$Medio$','$Alto$','$Muy Alto$','$Extremo$']
bounds = np.array([0, 2.5, 5.5, 7.5, 10.5, 16 ])

fig, ax= plt.subplots()

for span, color in zip(itertools.pairwise(bounds), colors):
    ax.axhspan(*span, facecolor=color, alpha=0.8)
ax.margins(0)

cmap = mpl.colors.ListedColormap(colors)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

ax_pos = ax.get_position().bounds
cbar_ay = fig.add_axes([0.93, ax_pos[1], 0.2, ax_pos[3]])
cbar = plt.colorbar(mpl.cm.ScalarMappable(cmap=cmap, norm=norm), cax=cbar_ay, orientation="vertical", spacing='proportional')
cbar.ax.set_axis_off()

for y, lab in zip(bounds[:-1] + np.diff(bounds) / 2, labels):
    cbar.ax.text(.5, y, lab, ha='center', va='center')

相关问题