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

Get certified in Microsoft Fabric—for free! For a limited time, get a free DP-600 exam voucher to use by the end of 2024. Register now

Reply
powerbi2srm
Resolver II
Resolver II

How to display a dynamic map in Power BI using Python script

Hi!
I'm trying to display a dynamic map in Power BI through Python script editor. This is my code in Python (it works properly)

 

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

# Read geojson
mapa = gpd.read_file('spain_map.json')
# Read xlsx
pedidos_venta = pd.read_excel("sale_orders.xlsx")
# Merge by the common column
mapa_pedidos_venta = mapa.merge(pedidos_venta, left_on='acom_name', right_on='acon_name_')

# Plot map 
fig, ax = plt.subplots(figsize=(10, 6))
mapa_pedidos_venta.plot(ax=ax)
plt.show()

 

As I'm looking for getting a dynamic map in Power BI, I've changed this code for Python script editor of Power BI using fields of my Power BI dataset. This dataset has been imported merging the two files mentioned above. I want to use three fields:

  • acom_name: names of Spain regions.
  • pedidos_venta: number of sale order by region
  • geometry: coordenates of regions (imported of geojson file).

Power BI automatically generates the next dataframe in Python script editor:

 

dataset = pandas.DataFrame(geometry, pedidos_venta, acom_name)

 

And then this is that I've tried:

 

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 6))
dataset.plot(ax=ax)
plt.show()

 

However, I didn't get a map visualization. This code now show me a line graph. Can someone help me, please? Thank you so much!!
Captura.PNG

1 ACCEPTED SOLUTION
powerbi2srm
Resolver II
Resolver II

Firstly, it's neccesary to drag your variables onto the map (in this case, 'acon_name' and 'pedidos_venta'). Then this code will work properly:

 

 

import geopandas as gpd
import matplotlib.pyplot as plt

# Reading geojson
mapa = gpd.read_file('spain_map.json')

# Merging by the common column
mapa_pedidos_venta = mapa.merge(dataset, left_on='acom_name', right_on=dataset.acom_name)

# Drawing the map
mapa_pedidos_venta.plot(edgecolor='black', linewidth=1)

# Displaying the map
plt.show()

 

 

 It's possible to format your map with something like:

 

 

# Defining colors:
def color_range(row):
    if row['pedidos_venta'] > 3000:
        return '#00ff00'
    elif round(row['pedidos_venta'],4) >= 2000:
        return '#FFFF00'
    else:
        return '#FF0000'

# Asigning colors:
color_map = mapa_pedidos_venta.apply(asignar_color,axis=1)

#Changing figsize and dpi
plt.rcParams["figure.figsize"] = (50,25)
plt.rcParams['figure.dpi'] = 140

# Plotting the map
mapa_pedidos_venta.plot(color=color_map, edgecolor='black', linewidth=1)

#Adding labels
for idx, row in mapa_pedidos_venta.iterrows():
    etiqueta = '{:.2%}'.format(row['pedidos_venta'])
    plt.annotate(text=etiqueta, xy=row['geometry'].centroid.coords[0], ha='center', fontsize=40)

# Removing axes
plt.axis('off')

# Displaying the map
plt.show()

 

 

 

View solution in original post

1 REPLY 1
powerbi2srm
Resolver II
Resolver II

Firstly, it's neccesary to drag your variables onto the map (in this case, 'acon_name' and 'pedidos_venta'). Then this code will work properly:

 

 

import geopandas as gpd
import matplotlib.pyplot as plt

# Reading geojson
mapa = gpd.read_file('spain_map.json')

# Merging by the common column
mapa_pedidos_venta = mapa.merge(dataset, left_on='acom_name', right_on=dataset.acom_name)

# Drawing the map
mapa_pedidos_venta.plot(edgecolor='black', linewidth=1)

# Displaying the map
plt.show()

 

 

 It's possible to format your map with something like:

 

 

# Defining colors:
def color_range(row):
    if row['pedidos_venta'] > 3000:
        return '#00ff00'
    elif round(row['pedidos_venta'],4) >= 2000:
        return '#FFFF00'
    else:
        return '#FF0000'

# Asigning colors:
color_map = mapa_pedidos_venta.apply(asignar_color,axis=1)

#Changing figsize and dpi
plt.rcParams["figure.figsize"] = (50,25)
plt.rcParams['figure.dpi'] = 140

# Plotting the map
mapa_pedidos_venta.plot(color=color_map, edgecolor='black', linewidth=1)

#Adding labels
for idx, row in mapa_pedidos_venta.iterrows():
    etiqueta = '{:.2%}'.format(row['pedidos_venta'])
    plt.annotate(text=etiqueta, xy=row['geometry'].centroid.coords[0], ha='center', fontsize=40)

# Removing axes
plt.axis('off')

# Displaying the map
plt.show()

 

 

 

Helpful resources

Announcements
November Carousel

Fabric Community Update - November 2024

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

Live Sessions with Fabric DB

Be one of the first to start using Fabric Databases

Starting December 3, join live sessions with database experts and the Fabric product team to learn just how easy it is to get started.

Las Vegas 2025

Join us at the Microsoft Fabric Community Conference

March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount! Early Bird pricing ends December 9th.

Nov PBI Update Carousel

Power BI Monthly Update - November 2024

Check out the November 2024 Power BI update to learn about new features.