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.
1条答案
按热度按时间tquggr8v1#
我想绘制第二个轴并用
axhspan
填充它要容易得多,就像绘制主轴一样,但是如果你想使用颜色条,你可以如下所示: