Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Compete to become Power BI Data Viz World Champion! First round ends August 18th. Get started.

Reply
Maty_B
Regular Visitor

Color de fondo de un objeto visual de Python

Hola comunidad,

Me encuentro desarrollando un gráfico de ingresos vs costos mediante un objeto visual de python (funciona todo correctamente), lo que sucede, es que al momento de publicar el power bi y visualizarlo desde la web, el color de fondo del gráfico, inicializado bajo el siguiente codigo (facecolor).

fig, ax = plt.subplots(dpi=100, figsize=(5, 2.8), facecolor='#F0F0F0')

En la aplicación de escritorio ejecuta con normalidad, como en la siguiente imagen

 

Maty_B_0-1667260598935.png

En Power Bi, posee un alpha del 100% para su fondo

Maty_B_1-1667260644199.png

Por lo que no me explico por que da el siguiente resultado

Maty_B_2-1667260695019.png

Alguna idea de como resolver este comportamiento?

Adjunto el codigo del gráfico implementado, gracias de antemano!

# dataset = pandas.DataFrame(Ingresos, Costos, Fecha - Mes, Fecha - Num Mes)
# dataset = dataset.drop_duplicates()

# Pegue o escriba aquí el código de script:

# Importar librerias
from datetime import datetime
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from operator import itemgetter
import numpy as np

# Convierte un valor a uno alphanumérico
def valor_alphanumerico(valor):
    nuevo_valor = 0

    if valor < 1000:
        nuevo_valor = str(valor)
    elif valor < 1000000:
        nuevo_valor = str(round(valor / 1000, 1)) + 'K'
    elif valor < 1000000000:
        nuevo_valor = str(round(valor / 1000000, 1)) + 'M'

    return nuevo_valor

def prefijo(valor):
    valor_prefijo = 0

    if valor < 1000:
        valor_prefijo = 1
    elif valor < 1000000:
        valor_prefijo = 1000
    elif valor < 1000000000:
        valor_prefijo = 1000000

    return valor_prefijo

# Construcción del marco principal
fig, ax = plt.subplots(dpi=100, figsize=(5, 2.8), facecolor='#F0F0F0')

# Encontrar la lista de las características objetivo (identificador de mes, acumulada de ingresos, acumulada de costos y su frecuencia) para obtener datos medios de los meses
dataset_agrupado = dataset.groupby('Fecha - Mes').mean()

lista_num_meses = dataset_agrupado['Fecha - Num Mes']
lista_meses = dataset_agrupado.index
lista_meses_ingresos = dataset_agrupado['Ingresos']
lista_meses_costos = dataset_agrupado['Costos']
lista_caracteristicas = [[lista_num_meses[i], lista_meses[i], lista_meses_ingresos[i], lista_meses_costos[i]] for i in range(len(lista_num_meses))]


lista_caracteristicas.sort(key=itemgetter(0), reverse=False)

# Generar las funciones/rangos iniciales para dibujar el gráfico
eje_x01 = [x for x in range(len(lista_caracteristicas))]
eje_y01 = [lista_caracteristicas[x][2] for x in range(len(lista_caracteristicas))]
eje_x02 = [x for x in range(len(lista_caracteristicas))]
eje_y02 = [lista_caracteristicas[x][3] for x in range(len(lista_caracteristicas))]

# Suavizar -si es posible- las funciones/rangos de las rectas de ingresos y costos
if len(eje_x01) < 4:
    modelo_interpolacion01 = interp1d(eje_x01, eje_y01, kind="linear")
    modelo_interpolacion02 = interp1d(eje_x02, eje_y02, kind='linear')
else:
    modelo_interpolacion01 = interp1d(eje_x01, eje_y01, kind="cubic")
    modelo_interpolacion02 = interp1d(eje_x02, eje_y02, kind='cubic')

x01 = np.linspace(np.min(eje_x01), np.max(eje_x01), 500)
y01 = modelo_interpolacion01(x01)
x02 = np.linspace(np.min(eje_x02), np.max(eje_x02), 500)
y02 = modelo_interpolacion02(x02)

# Crear las lineas de las funciones
line_x01, = ax.plot(x01, y01, color='#1FC78F', label='Ingresos', alpha=0.3)
line_x02, = ax.plot(x02, y02, color='#F2492A', label='Costos', alpha=0.3)

# Generar etiquetas para el gráfico
rango_eje_x = [i for i in range(len(lista_caracteristicas))]
etiqueta_eje_x = [lista_caracteristicas[i][1] for i in rango_eje_x]
max_ingreso = np.max(lista_meses_ingresos)
max_costo = np.max(lista_meses_costos)
max_eje_y = np.max([max_ingreso, max_costo])
min_ingreso = np.min(lista_meses_ingresos)
min_costo = np.min(lista_meses_costos)
min_eje_y = np.min([min_ingreso, min_costo])
rango_eje_y = [i for i in range(int(min_eje_y), int(max_eje_y) + 1, int((max_eje_y - min_eje_y)/6))]
etiqueta_eje_y = ['$' + valor_alphanumerico(i) for i in rango_eje_y]

# Dibujar nuevas etiquetas al gráfico
ax.set_xticks(rango_eje_x)
ax.set_xticklabels(etiqueta_eje_x)
ax.set_yticks(rango_eje_y) 
ax.set_yticklabels(etiqueta_eje_y)

# Pintar el área entre las rectas
ax.fill_between(x01, y01, y02, where=(y01 > y02), interpolate=True, color="#1FC78F", alpha=0.3, label="Ganancias")

ax.fill_between(x02, y01, y02, where=(y01 <= y02), interpolate=True, color="#F2492A", alpha=0.3, label="Perdidas")

ax.spines['bottom'].set_color('#CCCCCC')
for spine in ['right', 'top', 'left']:
    ax.spines[spine].set_visible(False)
ax.tick_params(width=0, colors='#666666', labelsize=8)
ax.set_facecolor('#F0F0F0')

# Mostrar la legenda de los datos
legendas, etiquetas = plt.gca().get_legend_handles_labels()
orden = [0, 2, 1, 3]

ax.legend([legendas[i] for i in orden], [etiquetas[i] for i in orden], bbox_to_anchor=(0., -0.02, 1., -.102), mode='expand', facecolor='#FFFFFF', ncol=4, fontsize=8)
plt.tight_layout()

# Generar anotaciones respecto a los máx y min de los datos
lista_num_meses_ordenada = [lista_caracteristicas[i][0] for i in range(len(lista_caracteristicas))]
lista_meses_ingresos_ordenada = [lista_caracteristicas[i][2] for i in range(len(lista_caracteristicas))]
lista_meses_costos_ordenada = [lista_caracteristicas[i][3] for i in range(len(lista_caracteristicas))]

lista_indices = [lista_meses_ingresos_ordenada.index(max_ingreso),
                 lista_meses_ingresos_ordenada.index(min_ingreso),
                 lista_meses_costos_ordenada.index(max_costo),
                 lista_meses_costos_ordenada.index(min_costo)]
for i in range(4):
    if i == 0:
        color_punto = '#1FC78F'
        pos_y = max_ingreso + (max_eje_y - min_eje_y)/12
        etiqueta_anotacion = 'Máx: ' + '$' + valor_alphanumerico(max_ingreso)
    elif i == 1:
        color_punto = '#1FC78F'
        pos_y = min_ingreso + (max_eje_y - min_eje_y)/12
        etiqueta_anotacion = 'Min: ' + '$' + valor_alphanumerico(min_ingreso)
    elif i == 2:
        color_punto = '#F2492A'
        pos_y = max_costo + (max_eje_y - min_eje_y)/12
        etiqueta_anotacion = 'Máx: ' + '$' + valor_alphanumerico(max_costo)
    else:
        color_punto = '#F2492A'
        pos_y = min_costo  + (max_eje_y - min_eje_y)/12
        etiqueta_anotacion = 'Min: ' + '$' + valor_alphanumerico(min_costo)

    if lista_indices[i] == len(lista_num_meses_ordenada) - 1:
        orientacion = 'right'
    elif lista_indices[i] == 0:
        orientacion = 'left'
    else:
        orientacion = 'center'

    ax.text(lista_indices[i], pos_y, etiqueta_anotacion, size=8, ha=orientacion, color='#666666')
    ax.plot(lista_indices[i], pos_y - (max_eje_y - min_eje_y)/12, marker=".", color=color_punto)

# Mostrar gráfico
plt.show()

 

2 REPLIES 2
v-xiaosun-msft
Community Support
Community Support

Hi @Maty_B ,

 

According to your description, I made a sample and here is my solution.

Please try to turn down the "transparency".

vxiaosunmsft_0-1667294500895.pngvxiaosunmsft_1-1667294560995.png

 

Best Regards,
Community Support Team _ xiaosun

If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

Hello, thanks for answering, regarding what is proposed, I leave the following images, well, the background of the object is not the problem, but the background of the graph generated by python, and it only happens when it is executed from the online work area, well , in the desktop application this fact does not occur

 

-from the web

Maty_B_0-1667340146517.png

-from the desktop application

Maty_B_1-1667340155133.png

 

Helpful resources

Announcements
August Power BI Update Carousel

Power BI Monthly Update - August 2025

Check out the August 2025 Power BI update to learn about new features.

August 2025 community update carousel

Fabric Community Update - August 2025

Find out what's new and trending in the Fabric community.

Top Solution Authors