Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

363
Vistas
How can I convert numbers to a color scale in matplotlib?

I'm making a bar plot and I want the colors of the bars to vary from red to blue according to a color gradient. I have a dimension of the data frame that tells me where on the red-blue scale each bar should be. My current method is to manually convert these values to RGB colors by linearly interpolating between the RGB red and blue colors but I want an automatic way of converting my numeric values to a color scale. I also need to be able to have a colorbar legend to help interpret it.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

It's pretty straight forward to create a barchart and set the bar colors according to a value from the dataframe. A colormap and a normalization instance help converting the values to colors, which are understood by the color argument of matplotlib.Axes.bar. The colorbar is then created from a ScalarMappable using the same normalization and colormap as the bars.

enter image description here

import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np; np.random.seed(0)
import pandas as pd

x = np.arange(12)
y = np.random.rand(len(x))*51
c = np.random.rand(len(x))*3+1.5
df = pd.DataFrame({"x":x,"y":y,"c":c})

cmap = plt.cm.rainbow
norm = matplotlib.colors.Normalize(vmin=1.5, vmax=4.5)

fig, ax = plt.subplots()
ax.bar(df.x, df.y, color=cmap(norm(df.c.values)))
ax.set_xticks(df.x)

sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])  # only needed for matplotlib < 3.1
fig.colorbar(sm)

plt.show()

For using a custom colormap with bar plots see Barplot colored according a colormap?

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda