Forum Discussion

Capybara's avatar
Capybara
Regular Visitor
1 year ago
Solved

Python Visual (Waterfalldiagram) in PowerBI Services (Cloud) doesnt work

Dear all,

I've created a waterfall diagram in Power BI Desktop. It works without any issues with the Python script visualization. However, as soon as I upload the file to Power BI Services and generate a report to share across the company, the diagram disappears. In the visual center, the Python module is not displayed, and it seems that Python code cannot be used in Power BI Services. This is quite concerning, as I'm almost finished and it worked really well, but now it seems like my work has been undone. Could you please take a look and let me know if anyone has any tips?


PowerBI Desktop:

 

Error in PowerBI Services (Cloud):

import pandas as pd
import matplotlib.pyplot as plt

# In Power BI wird das Dataset bereits bereitgestellt. Falls nicht, wird hier ein Dummy-Dataset erstellt:
try:
    dataset
except NameError:
    data = {
        'Application': ['App A', 'App A', 'App A', 'App A',
                        'App B', 'App B', 'App B', 'App B'],
        'Week': ['Week 1', 'Week 2', 'Week 3', 'Week 4',
                 'Week 1', 'Week 2', 'Week 3', 'Week 4'],
        'Costs': [100, 150, 130, 170,
                  200, 180, 210, 230],
        'YearOnly': [2024, 2024, 2024, 2024,
                     2024, 2024, 2024, 2024]
    }
    dataset = pd.DataFrame(data)

# Füge das Jahr als eigene Spalte zur Woche hinzu
dataset["Week_Year"] = dataset["Week"] + " (" + dataset["YearOnly"].astype(str) + ")"

# Hole alle eindeutigen Anwendungen
applications = dataset['Application'].unique()
n_apps = len(applications)

# Erstelle Subplots – eine Zeile pro Anwendung
fig, axes = plt.subplots(n_apps, 1, figsize=(10, n_apps * 6), sharex=False)
if n_apps == 1:
    axes = [axes]  # Falls nur eine Anwendung vorliegt

# Für jede Anwendung:
for ax, app in zip(axes, applications):
    # Filtere die Daten für die jeweilige Anwendung und sortiere nach Week_Year
    app_data = dataset[dataset['Application'] == app].copy()
    app_data = app_data.sort_values(by="Week_Year").reset_index(drop=True)
    
    # Berechne Delta (Differenz der Kosten) – erste Woche als Startwert
    app_data["Delta"] = app_data["Costs"].diff().fillna(app_data["Costs"])
    
    # Berechne die kumulative Position (Boden der Balken)
    app_data["Position"] = app_data["Delta"].cumsum().shift(1).fillna(0)
    
    # Füge einen finalen Balken hinzu, der den Endwert anzeigt
    final_row = pd.DataFrame({
        "Week_Year": ["Final"],
        "Costs": [app_data["Costs"].iloc[-1]],
        "Delta": [app_data["Costs"].iloc[-1]],
        "Position": [0]  # Finaler Balken beginnt am Boden
    })
    app_data = pd.concat([app_data, final_row], ignore_index=True)
    
    # Farben: Grün für positive Delta, Rot für negative, Blau für den finalen Balken
    colors = ["green" if x > 0 else "red" for x in app_data["Delta"]]
    colors[-1] = "blue"
    
    # Berechne den maximalen y-Wert inkl. 20% Puffer
    max_y = (app_data["Position"] + app_data["Delta"]).max() * 1.2
    
    # Zeichne das Balkendiagramm
    ax.bar(app_data["Week_Year"].astype(str), app_data["Delta"], 
           bottom=app_data["Position"], color=colors, edgecolor='black')
    
    # Titel und Achsentitel setzen
    ax.set_title(f"Waterfall Diagram for {app}", fontsize=14)
    ax.set_xlabel("Week (Year)")
    ax.set_ylabel("Costs in €")
    
    # Werte auf den Balken anzeigen (mit Euro-Zeichen)
    for i in range(len(app_data)):
        ax.text(i, app_data["Position"].iloc[i] + app_data["Delta"].iloc[i] / 2, 
                f"€{app_data['Delta'].iloc[i]:.2f}", ha='center', va='center', fontsize=10, color='black')
    
    # Setze die Y-Achsen-Grenze
    ax.set_ylim(0, max_y)
    ax.set_xticklabels(app_data["Week_Year"].astype(str), rotation=45)

plt.tight_layout()
plt.show()

 

  • Python visuals mandate the use of a Personal Gateway when included in a published report.  Think hard, think twice before you want to commit to running that gateway.

4 Replies

  • Python visuals mandate the use of a Personal Gateway when included in a published report.  Think hard, think twice before you want to commit to running that gateway.

  • Anonymous's avatar
    Anonymous
    Not applicable

    Hi Capybara ,

    Thank you for the helpful response lbendlin  .
    I just wanted to kindly follow up to see if you had a chance to review the previous response provided by lbendlin . I hope it was helpful. If yes, please Accept the answer so that it will be helpful to others to find it quickly.

     

  • Anonymous's avatar
    Anonymous
    Not applicable

    Hi Capybara ,
    I wanted to check in on your situation regarding the issue. Have you resolved it? If you have, please consider marking the reply that helped you or sharing your solution. It would be greatly appreciated by others in the community who may have the same question

  • Anonymous's avatar
    Anonymous
    Not applicable

    Hi Capybara ,
    May I ask if you have gotten this issue resolved?
    If it is solved, please mark the helpful reply or share your solution and accept it as solution, it will be helpful for other members of the community who have similar problems as yours to solve it faster.

    Thank you.