
Python Visuals
- 32 installs
- 836 repo stars
- Updated July 29, 2026
- data-goblin/power-bi-agentic-development
Create Python visuals in Power BI PBIR reports using matplotlib and seaborn scripts injected into the report.
About
Guidance for creating Python visuals in PBIR reports with matplotlib and seaborn patterns. A developer uses it to add a Python-scripted chart to a Power BI report via the pbir CLI or direct JSON editing.
- Creates pythonVisual charts with matplotlib/seaborn
- Applies via pbir CLI or direct PBIR JSON edits
Python Visuals by the numbers
- 32 all-time installs (skills.sh)
- Ranked #1,096 of 2,064 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/data-goblin/power-bi-agentic-development --skill python-visualsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 32 |
|---|---|
| repo stars | ★ 836 |
| Last updated | July 29, 2026 |
| Repository | data-goblin/power-bi-agentic-development ↗ |
What it does
Create Python visuals in Power BI PBIR reports using matplotlib and seaborn scripts injected into the report.
Files
Python Visuals in Power BI (PBIR)
Report modification requires tooling. Two paths exist:
1. `pbir` CLI (preferred) -- use thepbircommand and thepbir-cliskill. Install withuv tool install pbir-cliorpip install pbir-cli. Check availability withpbir --version.
2. Direct JSON modification -- ifpbiris not available, use thepbir-formatskill (pbip plugin) for PBIR JSON structure and patterns. Validate every change withjq empty <file.json>.
>
If neither thepbir-cliskill nor thepbir-formatskill is loaded, ask the user to install the appropriate plugin before proceeding with report modifications.
Python visuals execute matplotlib/seaborn scripts to render static PNG images on the Power BI canvas. Prefer seaborn over raw matplotlib for cleaner syntax and better defaults -- it handles most chart types with less code.
Visual Identity
- visualType:
pythonVisual - Data role:
Values(columns and measures, multiple allowed) - Data variable:
dataset(pandas DataFrame, auto-injected) - Row limit: 150,000 rows
- Output: Static PNG at 72 DPI -- no interactivity
Workflow: Creating a Python Visual
Step 1: Add the Visual
Create the visual.json file manually (see pbir-format skill in the pbip plugin for JSON structure) with visualType: pythonVisual, field bindings for the columns and measures you need (use Values:Table.Column or Values:Table.Measure format), and position/size as required.
Step 2: Write the Script
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(dataset["Date"], dataset["Sales"], color="#5B8DBE")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.show() # MANDATORYCritical rules:
plt.show()is mandatory as the final line -- nothing renders without itdatasetis auto-injected as a pandas DataFrame; do not create it- Column names match the
nativeQueryRef(display name) from field bindings - Only the last
plt.show()call renders; multiple figures not supported
Step 2b: Review
Before presenting the script to the user, dispatch the python-reviewer agent to validate correctness and provide design feedback.
Step 3: Inject the Script
Set the script content in the visual's objects.script[0].properties.source literal value (see PBIR Format section below).
Escaping rules for visual.json injection:
The script must be encoded as a single-quoted DAX literal string inside expr.Literal.Value:
- Newlines in the script become
\nin the JSON string - Double quotes inside the script (e.g.,
"#5B8DBE") become\"in the JSON string - The entire script is wrapped in single quotes:
'import matplotlib...\nplt.show()' - See
examples/visual/for a complete real-world visual.json showing this encoding
Step 4: Validate
Validate JSON syntax with jq empty <visual.json> and inspect the visual.json to confirm script content and field bindings.
PBIR Format
Scripts are stored in visual.objects.script[0].properties:
{
"source": {"expr": {"Literal": {"Value": "'import matplotlib.pyplot as plt\\n...\\nplt.show()'"}}},
"provider": {"expr": {"Literal": {"Value": "'Python'"}}}
}The CLI handles all escaping automatically.
Supported Libraries
Power BI Service (Python 3.11)
| Package | Version | Purpose |
|---|---|---|
| matplotlib | 3.8.4 | Primary plotting |
| seaborn | 0.13.2 | Statistical visualization |
| numpy | 2.0.0 | Numerical computing |
| pandas | 2.2.2 | Data manipulation |
| scipy | 1.13.1 | Scientific computing |
| scikit-learn | 1.5.0 | Machine learning |
| statsmodels | 0.14.2 | Statistical models |
| pillow | 10.4.0 | Image processing |
Not supported: plotly, bokeh, altair (networking blocked in Service).
Full package list: https://learn.microsoft.com/power-bi/connect-data/service-python-packages-support
Desktop
Any locally installed package works without restriction.
Best Practices
1. Always call `plt.show()` -- mandatory, must be the final line 2. Use `figsize=(w, h)` to match container aspect ratio (72 DPI output) 3. Remove chart chrome -- ax.spines["top"].set_visible(False) etc. 4. Use hex colors matching the report theme 5. Keep scripts simple -- 5-min timeout Desktop, 1-min Service 6. Minimize transforms -- do heavy computation in DAX/Power Query instead 7. Use `try/except` for robustness in production scripts 8. Copy data first -- data = dataset.copy() before manipulation
Limitations
| Constraint | Desktop | Service |
|---|---|---|
| Output | Static PNG, 72 DPI | Static PNG, 72 DPI |
| Timeout | 5 minutes | 1 minute |
| Row limit | 150,000 | 150,000 |
| Payload | -- | 30 MB |
| Networking | Unrestricted | Blocked |
| Gateway | Personal only | Personal only |
| Cross-filter FROM | Not supported | Not supported |
| Receive cross-filter | Yes | Yes |
| Publish to web | Not supported | Not supported |
| Embed (app-owns-data) | Not supported | Not supported |
Script Structure Template
import matplotlib.pyplot as plt
import numpy as np
# 1. Guard against empty data
if dataset.empty:
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.text(0.5, 0.5, "No data available", ha='center', va='center', fontsize=14, color='#888888')
ax.axis('off')
plt.show()
else:
# 2. Data preparation (dataset is auto-injected)
data = dataset.copy()
# 3. Create figure with explicit size
fig, ax = plt.subplots(figsize=(8, 4))
# 4. Plot
ax.plot(data["X"], data["Y"], color="#5B8DBE", linewidth=2)
# 5. Style
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.grid(axis="y", alpha=0.3)
# 6. Layout and render
plt.tight_layout()
plt.show()When to Use a Script Visual
Reach for a Python visual only when all of the following hold:
- The chart has no native equivalent and no reasonable Deneb spec
- The value is in a statistical computation that must run at render time (model fit, kernel density, forecast band), not just a shape Vega could draw
- The visual does not need to be a cross-filter source, hover tooltips, publish-to-web, or app-owns-data embed
- The report is served in a Pro/PPU or higher capacity with a Fabric-enabled region
If interactivity or cross-filtering matters, use Deneb (a static PNG cannot be a selection source). If the need is a small inline mark (sparkline, bar, status pill), use an SVG measure (no row cap, no timeout, no licensing/region gate, renders under publish-to-web). The script visual's niche is narrow: compute-at-render statistical plots for internal or org consumption.
Python vs R once a script visual is the right call: use Python when the computation leans on scikit-learn, statsmodels, or scipy, or when surrounding report logic is already Python. Use R for publication-quality statistical defaults and packages with no Python peer (forecast, corrplot, pheatmap, ridgeline/violin). Where equal, default to whichever language the report's other scripts use; mixing doubles the publish-time package surface to validate.
Do not default to a script visual because a chart type "looks statistical." A box plot, lollipop, or dumbbell is an SVG-measure or Deneb job; reserve scripts for charts that genuinely compute.
References
- `references/data-model.md` --
datasetgrouping mechanic, the row/byte caps, and how to force per-row input - `references/community-examples.md` -- seaborn gallery examples organized by chart type, plus matplotlib and Python Graph Gallery links
- `references/chart-patterns.md` -- Common matplotlib/seaborn chart patterns (bar, heatmap, donut, KPI, area)
- `examples/script/` -- Standalone Python scripts (bar-chart, trend-line) -- ready to inject into visual.json after escaping
- `examples/visual/bar-chart.json` -- PBIR visual.json: horizontal stacked bar with PY comparison lines and % change labels
- `examples/visual/kpi-card.json` -- PBIR visual.json: text-based KPI with value, % change indicator, and PY comparison
- `examples/visual/trend-line.json` -- PBIR visual.json: area chart with line plot and monthly x-axis
Fetching Docs
To retrieve current Python visual / package support docs, use microsoft_docs_search + microsoft_docs_fetch (MCP) if available, otherwise mslearn search + mslearn fetch (CLI). Search based on the user's request and run multiple searches as needed to ensure sufficient context before proceeding.
Related Skills
- `pbi-report-design` -- Layout and design best practices
- `r-visuals` -- R Script visuals (same concept, different language)
- `deneb-visuals` -- Vega/Vega-Lite visuals (interactive, vector-based alternative)
- `svg-visuals` -- SVG via DAX measures (lightweight inline graphics)
- `pbir-format` (pbip plugin) -- PBIR JSON format reference
import matplotlib.pyplot as plt
# dataset is auto-injected as a pandas DataFrame
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(dataset.iloc[:, 0], dataset.iloc[:, 1], color="#5B8DBE")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.set_title("Sales by Category", fontsize=14, fontweight="bold")
plt.tight_layout()
plt.show()
import matplotlib.pyplot as plt
# dataset is auto-injected as a pandas DataFrame
fig, ax = plt.subplots(figsize=(8, 3))
x = range(len(dataset))
y = dataset.iloc[:, 0]
ax.fill_between(x, 0, y, alpha=0.12, color="#5B8DBE")
ax.plot(
y.values,
color="#5B8DBE",
linewidth=2.4,
marker="o",
markerfacecolor="white",
markeredgecolor="#5B8DBE",
markersize=6,
)
ax.grid(axis="y", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.show()
{
"$schema": "https://developer.microsoft.com/json-schemas/fabric/item/report/definition/visualContainer/2.2.0/schema.json",
"name": "python_bar_chart",
"position": {
"x": 20,
"y": 250,
"z": 2,
"height": 450,
"width": 720,
"tabOrder": 4
},
"visual": {
"visualType": "pythonVisual",
"visualContainerObjects": {
"title": [
{
"properties": {
"show": {
"expr": {
"Literal": {
"Value": "false"
}
}
}
}
}
]
},
"query": {
"queryState": {
"Values": {
"projections": [
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders"
}
},
"Property": "Order Lines"
}
},
"queryRef": "Orders.Order Lines",
"nativeQueryRef": "Order Lines"
},
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders",
"Schema": "extension"
}
},
"Property": "Order Lines (PY)"
}
},
"queryRef": "Orders.Order Lines (PY)",
"nativeQueryRef": "Order Lines (PY)"
},
{
"field": {
"Column": {
"Expression": {
"SourceRef": {
"Entity": "Customers"
}
},
"Property": "Key Account Name"
}
},
"queryRef": "Customers.Key Account Name",
"nativeQueryRef": "Key Account Name"
}
]
}
},
"sortDefinition": {
"sort": [
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders"
}
},
"Property": "Order Lines"
}
},
"direction": "Descending"
}
],
"isDefaultSort": true
}
},
"objects": {
"script": [
{
"properties": {
"source": {
"expr": {
"Literal": {
"Value": "'import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import FuncFormatter\n\n# Professional color palette\nCOLORS = {\n \"bar_fill\": \"#7FA9C7\",\n \"py_line\": \"#6C757D\",\n \"gray_700\": \"#495057\",\n \"gray_600\": \"#6C757D\",\n \"positive\": \"#1971c2\",\n \"negative\": \"#c2255c\"\n}\n\n# Get top 8 accounts\ndataset_top = dataset.nlargest(8, \"Order Lines\")\n\n# Calculate metrics\ndataset_top[\"pct_change\"] = (dataset_top[\"Order Lines\"] - dataset_top[\"Order Lines (PY)\"]) / dataset_top[\"Order Lines (PY)\"]\ndataset_top[\"arrow\"] = dataset_top[\"pct_change\"].apply(lambda x: \"\\u25B2\" if x > 0 else \"\\u25BC\")\ndataset_top[\"label_color\"] = dataset_top[\"pct_change\"].apply(lambda x: COLORS[\"positive\"] if x > 0 else COLORS[\"negative\"])\n\n# Format function\ndef format_thousands(val):\n if val >= 100000:\n return f\"{round(val/1000)}K\"\n elif val >= 10000:\n return f\"{val/1000:.1f}K\"\n else:\n return f\"{val/1000:.2f}K\"\n\n# Create data labels\ndataset_top[\"data_label\"] = dataset_top.apply(\n lambda row: f\"{format_thousands(row['Order Lines'])} ({row['arrow']}{abs(row['pct_change'])*100:.0f}%)\",\n axis=1\n)\n\n# Reverse order for bottom-to-top display\ndataset_top = dataset_top.iloc[::-1].reset_index(drop=True)\n\n# Create figure\nfig, ax = plt.subplots(figsize=(10, 6.3))\n\nmax_val = dataset_top[\"Order Lines\"].max()\nx_range = [-max_val * 0.35, max_val * 1.18]\n\ny_positions = np.arange(len(dataset_top))\n\n# Draw bars\nax.barh(\n y_positions,\n dataset_top[\"Order Lines\"],\n height=0.65,\n color=COLORS[\"bar_fill\"],\n alpha=0.65\n)\n\n# Draw PY comparison lines\nfor i, row in dataset_top.iterrows():\n ax.plot(\n [row[\"Order Lines (PY)\"], row[\"Order Lines (PY)\"]],\n [i - 0.4, i + 0.4],\n color=COLORS[\"py_line\"],\n linewidth=3,\n solid_capstyle=\"round\"\n )\n\n# Add data labels outside bars\nfor i, row in dataset_top.iterrows():\n ax.text(\n row[\"Order Lines\"] + (max_val * 0.02),\n i,\n row[\"data_label\"],\n va=\"center\", ha=\"left\",\n fontsize=8,\n fontweight=\"bold\",\n color=row[\"label_color\"]\n )\n\n# Add account names on left\nfor i, row in dataset_top.iterrows():\n ax.text(\n -max_val * 0.02,\n i,\n row[\"Key Account Name\"],\n va=\"center\", ha=\"right\",\n fontsize=9,\n fontweight=\"bold\",\n color=row[\"label_color\"]\n )\n\n# Configure axes\nax.set_yticks([])\nax.set_xlim(x_range)\nax.set_xlabel(\"Order Lines\", fontsize=11, color=COLORS[\"gray_700\"])\n\n# X-axis formatting\ndef format_k(x, pos):\n if x >= 0:\n return f\"{int(round(x/1000))}K\"\n return \"\"\n\nax.xaxis.set_major_formatter(FuncFormatter(format_k))\n\n# Clean styling\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nax.spines[\"left\"].set_visible(False)\nax.spines[\"bottom\"].set_visible(False)\nax.grid(False)\n\n# Tick styling\nax.tick_params(\n axis=\"x\",\n labelsize=10,\n colors=COLORS[\"gray_600\"],\n length=0\n)\n\nplt.tight_layout()\nplt.show()'"
}
}
},
"provider": {
"expr": {
"Literal": {
"Value": "'Python'"
}
}
}
}
}
]
},
"drillFilterOtherVisuals": true
}
}
{
"$schema": "https://developer.microsoft.com/json-schemas/fabric/item/report/definition/visualContainer/2.2.0/schema.json",
"name": "python_kpi_card",
"position": {
"x": 20,
"y": 65,
"z": 0,
"height": 165,
"width": 260,
"tabOrder": 1
},
"visual": {
"visualType": "pythonVisual",
"visualContainerObjects": {
"title": [
{
"properties": {
"show": {
"expr": {
"Literal": {
"Value": "false"
}
}
}
}
}
]
},
"query": {
"queryState": {
"Values": {
"projections": [
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders"
}
},
"Property": "Order Lines"
}
},
"queryRef": "Orders.Order Lines",
"nativeQueryRef": "Order Lines"
},
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders",
"Schema": "extension"
}
},
"Property": "Order Lines (PY)"
}
},
"queryRef": "Orders.Order Lines (PY)",
"nativeQueryRef": "Order Lines (PY)"
},
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders",
"Schema": "extension"
}
},
"Property": "Order Lines vs. PY %"
}
},
"queryRef": "Orders.Order Lines vs. PY %",
"nativeQueryRef": "Order Lines vs. PY %"
}
]
}
},
"sortDefinition": {
"sort": [
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders"
}
},
"Property": "Order Lines"
}
},
"direction": "Descending"
}
],
"isDefaultSort": true
}
},
"objects": {
"script": [
{
"properties": {
"source": {
"expr": {
"Literal": {
"Value": "'import matplotlib.pyplot as plt\n\n# Professional color palette\nCOLORS = {\n \"gray_900\": \"#212529\",\n \"gray_600\": \"#6C757D\",\n \"gray_500\": \"#868E96\",\n \"positive\": \"#1971c2\",\n \"negative\": \"#c2255c\"\n}\n\n# Calculate metrics\ncurrent = dataset[\"Order Lines\"].sum()\nprior_year = dataset[\"Order Lines (PY)\"].sum()\npercent_change = dataset[\"Order Lines vs. PY %\"].mean()\n\n# Format value to K format\ndef format_thousands(val):\n if val >= 100000:\n return f\"{round(val/1000)}K\"\n elif val >= 10000:\n return f\"{val/1000:.1f}K\"\n else:\n return f\"{val/1000:.2f}K\"\n\n# Determine performance color and arrow\nif percent_change > 0:\n perf_color = COLORS[\"positive\"]\n arrow = \"\\u25B2\"\nelse:\n perf_color = COLORS[\"negative\"]\n arrow = \"\\u25BC\"\n\n# Create figure\nfig, ax = plt.subplots(figsize=(3.6, 2.3))\nax.set_xlim(0, 1)\nax.set_ylim(0, 1)\nax.axis(\"off\")\n\n# Label at top\nax.text(\n 0.5, 0.85,\n \"Order Lines\",\n ha=\"center\", va=\"center\",\n fontsize=10,\n fontweight=\"bold\",\n color=COLORS[\"gray_600\"]\n)\n\n# Main value\nax.text(\n 0.5, 0.55,\n format_thousands(current),\n ha=\"center\", va=\"center\",\n fontsize=28,\n fontweight=\"bold\",\n color=COLORS[\"gray_900\"]\n)\n\n# Percentage change with arrow\nax.text(\n 0.5, 0.30,\n f\"{arrow} {abs(percent_change)*100:+.1f}%\",\n ha=\"center\", va=\"center\",\n fontsize=14,\n fontweight=\"bold\",\n color=perf_color\n)\n\n# Comparison text\nax.text(\n 0.5, 0.12,\n f\"vs. {format_thousands(prior_year)} (PY)\",\n ha=\"center\", va=\"center\",\n fontsize=8,\n color=COLORS[\"gray_500\"]\n)\n\nplt.tight_layout(pad=0)\nplt.show()'"
}
}
},
"provider": {
"expr": {
"Literal": {
"Value": "'Python'"
}
}
}
}
}
]
},
"drillFilterOtherVisuals": true
}
}
{
"$schema": "https://developer.microsoft.com/json-schemas/fabric/item/report/definition/visualContainer/2.2.0/schema.json",
"name": "python_trendline",
"position": {
"x": 300,
"y": 65,
"z": 1,
"height": 165,
"width": 600,
"tabOrder": 2
},
"visual": {
"visualType": "pythonVisual",
"visualContainerObjects": {
"title": [
{
"properties": {
"show": {
"expr": {
"Literal": {
"Value": "false"
}
}
}
}
}
]
},
"query": {
"queryState": {
"Values": {
"projections": [
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders"
}
},
"Property": "Order Lines"
}
},
"queryRef": "Orders.Order Lines",
"nativeQueryRef": "Order Lines"
},
{
"field": {
"Column": {
"Expression": {
"SourceRef": {
"Entity": "Date"
}
},
"Property": "Calendar Month (ie Jan)"
}
},
"queryRef": "Date.Calendar Month (ie Jan)",
"nativeQueryRef": "Calendar Month (ie Jan)"
}
]
}
}
},
"objects": {
"script": [
{
"properties": {
"source": {
"expr": {
"Literal": {
"Value": "'import matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter\n\n# Professional color palette\nCOLORS = {\n \"primary\": \"#5B8DBE\",\n \"gray_700\": \"#495057\",\n \"gray_600\": \"#6C757D\",\n \"gray_400\": \"#ADB5BD\"\n}\n\n# Month order for sorting\nmonth_order = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n\n# Create month factor and sort\ndataset[\"month_index\"] = dataset[\"Calendar Month (ie Jan)\"].apply(lambda x: month_order.index(x) if x in month_order else -1)\ndataset = dataset.sort_values(\"month_index\")\n\n# Create figure\nfig, ax = plt.subplots(figsize=(8.3, 2.3))\n\n# Fill area under line\nax.fill_between(\n dataset[\"month_index\"],\n 0,\n dataset[\"Order Lines\"],\n color=COLORS[\"primary\"],\n alpha=0.12\n)\n\n# Line plot\nax.plot(\n dataset[\"month_index\"],\n dataset[\"Order Lines\"],\n color=COLORS[\"primary\"],\n linewidth=2.4,\n marker=\"o\",\n markerfacecolor=\"white\",\n markeredgecolor=COLORS[\"primary\"],\n markersize=6,\n markeredgewidth=3\n)\n\n# X-axis: month labels\nax.set_xticks(range(12))\nax.set_xticklabels(month_order)\n\n# Y-axis: K format\ndef format_k(x, pos):\n return f\"{int(round(x/1000))}K\"\n\nax.yaxis.set_major_formatter(FuncFormatter(format_k))\n\n# Grid and spines\nax.grid(axis=\"y\", color=COLORS[\"gray_400\"], linewidth=0.6, alpha=0.5)\nax.grid(axis=\"x\", visible=False)\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nax.spines[\"left\"].set_visible(False)\nax.spines[\"bottom\"].set_visible(False)\n\n# Labels\nax.set_ylabel(\"Order Lines\", fontsize=9, color=COLORS[\"gray_700\"])\nax.set_xlabel(\"\")\n\n# Tick styling\nax.tick_params(\n axis=\"both\",\n labelsize=8,\n colors=COLORS[\"gray_600\"],\n length=0\n)\n\n# Set y-axis to start at 0\nax.set_ylim(bottom=0)\n\nplt.tight_layout()\nplt.show()'"
}
}
},
"provider": {
"expr": {
"Literal": {
"Value": "'Python'"
}
}
}
}
}
]
},
"drillFilterOtherVisuals": true
}
}
{
"$schema": "https://developer.microsoft.com/json-schemas/fabric/item/report/definition/visualContainer/2.7.0/schema.json",
"name": "1a2b3c4d5e6f7890",
"position": {
"x": 20,
"y": 80,
"z": 1,
"height": 635,
"width": 400,
"tabOrder": 1
},
"visual": {
"visualType": "pythonVisual",
"visualContainerObjects": {
"title": [
{
"properties": {
"show": {
"expr": {
"Literal": {
"Value": "true"
}
}
},
"text": {
"expr": {
"Literal": {
"Value": "'Python (matplotlib)'"
}
}
}
}
}
],
"subTitle": [
{
"properties": {
"show": {
"expr": {
"Literal": {
"Value": "false"
}
}
}
}
}
]
},
"query": {
"queryState": {
"Values": {
"projections": [
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders",
"Schema": "extension"
}
},
"Property": "Order Lines YTD"
}
},
"queryRef": "Orders.Order Lines YTD",
"nativeQueryRef": "Order Lines YTD"
},
{
"field": {
"Measure": {
"Expression": {
"SourceRef": {
"Entity": "Orders",
"Schema": "extension"
}
},
"Property": "Order Lines (PY) YTD"
}
},
"queryRef": "Orders.Order Lines (PY) YTD",
"nativeQueryRef": "Order Lines (PY) YTD"
},
{
"field": {
"Column": {
"Expression": {
"SourceRef": {
"Entity": "Date"
}
},
"Property": "Calendar Month (ie Jan)"
}
},
"queryRef": "Date.Calendar Month (ie Jan)",
"nativeQueryRef": "Calendar Month (ie Jan)"
}
]
}
}
},
"objects": {
"script": [
{
"properties": {
"source": {
"expr": {
"Literal": {
"Value": "'import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import FuncFormatter\n\n# Colors\nCOLORS = {\n \"current\": \"#5B8DBE\",\n \"py\": \"#D4A574\",\n \"gray_700\": \"#495057\",\n \"gray_600\": \"#6C757D\",\n \"gray_400\": \"#ADB5BD\"\n}\n\n# Month order\nmonth_order = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n\n# Sort by month\ndataset[\"month_index\"] = dataset[\"Calendar Month (ie Jan)\"].apply(lambda x: month_order.index(x) if x in month_order else -1)\ndataset = dataset.sort_values(\"month_index\")\n\n# Get last index\nlast_idx = len(dataset) - 1\n\n# Create figure with larger size\nfig, ax = plt.subplots(figsize=(5.5, 8.8))\n\n# Plot lines without markers\nax.plot(\n dataset[\"month_index\"],\n dataset[\"Order Lines YTD\"],\n color=COLORS[\"current\"],\n linewidth=3.5,\n label=\"Order Lines YTD\"\n)\n\nax.plot(\n dataset[\"month_index\"],\n dataset[\"Order Lines (PY) YTD\"],\n color=COLORS[\"py\"],\n linewidth=3.5,\n linestyle=\"--\",\n label=\"Order Lines (PY) YTD\"\n)\n\n# Add marker ONLY on last point for both lines\nax.plot(\n dataset.iloc[last_idx][\"month_index\"],\n dataset.iloc[last_idx][\"Order Lines YTD\"],\n marker=\"o\",\n markersize=12,\n markerfacecolor=\"white\",\n markeredgecolor=COLORS[\"current\"],\n markeredgewidth=3.5\n)\n\nax.plot(\n dataset.iloc[last_idx][\"month_index\"],\n dataset.iloc[last_idx][\"Order Lines (PY) YTD\"],\n marker=\"o\",\n markersize=12,\n markerfacecolor=\"white\",\n markeredgecolor=COLORS[\"py\"],\n markeredgewidth=3.5\n)\n\n# Add labels ONLY on last point\ndef format_k(val):\n return f\"{int(round(val/1000))}K\"\n\nax.text(\n dataset.iloc[last_idx][\"month_index\"] + 0.4,\n dataset.iloc[last_idx][\"Order Lines YTD\"],\n format_k(dataset.iloc[last_idx][\"Order Lines YTD\"]),\n fontsize=14,\n fontweight=\"bold\",\n color=COLORS[\"current\"],\n va=\"center\"\n)\n\nax.text(\n dataset.iloc[last_idx][\"month_index\"] + 0.4,\n dataset.iloc[last_idx][\"Order Lines (PY) YTD\"],\n format_k(dataset.iloc[last_idx][\"Order Lines (PY) YTD\"]),\n fontsize=14,\n fontweight=\"bold\",\n color=COLORS[\"py\"],\n va=\"center\"\n)\n\n# X-axis with breathing room for labels\nax.set_xlim(-0.5, 13.5)\nax.set_xticks(range(12))\nax.set_xticklabels(month_order, rotation=45, ha=\"right\", fontsize=13)\n\n# Y-axis with breathing room\nmax_val = max(dataset[\"Order Lines YTD\"].max(), dataset[\"Order Lines (PY) YTD\"].max())\nax.set_ylim(0, max_val * 1.15)\nax.yaxis.set_major_formatter(FuncFormatter(lambda x, p: f\"{int(round(x/1000))}K\"))\nax.set_ylabel(\"Order Lines YTD\", fontsize=14, color=COLORS[\"gray_700\"])\n\n# Grid and spines\nax.grid(axis=\"y\", color=COLORS[\"gray_400\"], linewidth=0.8, alpha=0.5)\nax.grid(axis=\"x\", visible=False)\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nax.spines[\"left\"].set_color(COLORS[\"gray_400\"])\nax.spines[\"bottom\"].set_color(COLORS[\"gray_400\"])\n\n# Legend\nax.legend(loc=\"upper left\", frameon=False, fontsize=13)\n\n# Styling\nax.tick_params(axis=\"both\", labelsize=13, colors=COLORS[\"gray_600\"], length=0)\n\n# Adjust layout with right margin for labels\nfig.subplots_adjust(right=0.85)\nplt.tight_layout(rect=[0, 0, 0.85, 1])\nplt.show()'"
}
}
},
"provider": {
"expr": {
"Literal": {
"Value": "'Python'"
}
}
}
}
}
]
},
"drillFilterOtherVisuals": true
}
}
Python Chart Patterns for Power BI
Common matplotlib/seaborn patterns for Python visuals. All scripts assume dataset is auto-injected as a pandas DataFrame.
Bar Chart
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(dataset["Category"], dataset["Value"], color="#5B8DBE")
ax.set_title("Sales by Category", fontsize=14, fontweight="bold")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.show()Horizontal Bar Chart with Comparison
import matplotlib.pyplot as plt
df = dataset.sort_values(dataset.columns[1], ascending=True).tail(8)
fig, ax = plt.subplots(figsize=(8, 5))
ax.barh(df.iloc[:,0], df.iloc[:,1], color="#7FA9C7", alpha=0.65, height=0.6)
# PY comparison markers
ax.scatter(df.iloc[:,2], df.iloc[:,0], color="#6C757D", marker="|", s=200, linewidths=2, zorder=3)
# Value labels
for i, (v, name) in enumerate(zip(df.iloc[:,1], df.iloc[:,0])):
ax.text(v + 0.5, i, f"{v:,.0f}", va="center", fontsize=10, fontweight="bold")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.set_xlabel("")
plt.tight_layout()
plt.show()Line Chart with Area Fill
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 3))
x = range(len(dataset))
y = dataset.iloc[:,0]
ax.fill_between(x, 0, y, alpha=0.12, color="#5B8DBE")
ax.plot(y.values, color="#5B8DBE", linewidth=2.4,
marker="o", markerfacecolor="white", markeredgecolor="#5B8DBE", markersize=6)
ax.grid(axis="y", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.show()Seaborn Heatmap
import matplotlib.pyplot as plt
import seaborn as sns
pivot = dataset.pivot_table(values=dataset.columns[2],
index=dataset.columns[0],
columns=dataset.columns[1])
fig, ax = plt.subplots(figsize=(8, 6))
sns.heatmap(pivot, annot=True, fmt=".0f", cmap="Blues", ax=ax,
linewidths=0.5, linecolor="white")
plt.tight_layout()
plt.show()Donut Chart
import matplotlib.pyplot as plt
colors = ["#5B8DBE", "#D4A574", "#8BA888", "#C97C7C", "#9B87B8", "#6B9B9E"]
fig, ax = plt.subplots(figsize=(5, 4))
wedges, texts = ax.pie(
dataset.iloc[:,1],
labels=dataset.iloc[:,0],
colors=colors[:len(dataset)],
startangle=90,
wedgeprops={"width": 0.4, "edgecolor": "white", "linewidth": 3}
)
ax.axis("equal")
plt.tight_layout()
plt.show()KPI Card (Text Only)
import matplotlib.pyplot as plt
value = dataset.iloc[:,0].sum()
fig, ax = plt.subplots(figsize=(3, 2))
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis("off")
ax.text(0.5, 0.7, "Revenue", ha="center", fontsize=10, color="#6C757D",
fontfamily="Segoe UI")
ax.text(0.5, 0.4, f"${value:,.0f}", ha="center", fontsize=24,
fontweight="bold", fontfamily="Segoe UI")
plt.tight_layout(pad=0)
plt.show()Scatter Plot with Regression
import matplotlib.pyplot as plt
import numpy as np
x = dataset.iloc[:,0].values
y = dataset.iloc[:,1].values
fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(x, y, color="#5B8DBE", alpha=0.6, s=50)
# Trend line
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
ax.plot(sorted(x), p(sorted(x)), "--", color="#C97C7C", linewidth=1.5)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.set_xlabel(dataset.columns[0], fontsize=11)
ax.set_ylabel(dataset.columns[1], fontsize=11)
plt.tight_layout()
plt.show()Histogram with KDE
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots(figsize=(7, 4))
sns.histplot(dataset.iloc[:,0], kde=True, color="#5B8DBE", ax=ax, bins=20)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.show()Box Plot
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots(figsize=(8, 4))
sns.boxplot(data=dataset, x=dataset.columns[0], y=dataset.columns[1],
palette="Blues", ax=ax)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.show()Color Palette Constants
Define at the top of any script to match report themes:
# Muted palette (works well with Power BI)
COLORS = ["#5B8DBE", "#D4A574", "#8BA888", "#C97C7C", "#9B87B8", "#6B9B9E"]
# Sentiment colors
COLOR_POSITIVE = "#4CAF50"
COLOR_NEGATIVE = "#F44336"
COLOR_NEUTRAL = "#9E9E9E"
# Sequential
CMAP = "Blues" # seaborn/matplotlib colormapPython / seaborn Community Examples
seaborn is the preferred charting library for Python visuals in Power BI (built on matplotlib). Use these gallery references when building Python visual scripts.
Seaborn Example Gallery (seaborn.pydata.org/examples/)
Regression
| Example | URL |
|---|---|
| Anscombe's Quartet | https://seaborn.pydata.org/examples/anscombes_quartet.html |
| Logistic Regression | https://seaborn.pydata.org/examples/logistic_regression.html |
| Multiple Regression | https://seaborn.pydata.org/examples/multiple_regression.html |
| Residual Plot | https://seaborn.pydata.org/examples/residplot.html |
| Regression Marginals | https://seaborn.pydata.org/examples/regression_marginals.html |
Scatter / Relational
| Example | URL |
|---|---|
| Different Scatter Variables | https://seaborn.pydata.org/examples/different_scatter_variables.html |
| Heat Scatter | https://seaborn.pydata.org/examples/heat_scatter.html |
| Scatter Bubbles | https://seaborn.pydata.org/examples/scatter_bubbles.html |
| Scatterplot Sizes | https://seaborn.pydata.org/examples/scatterplot_sizes.html |
| Layered Bivariate Plot | https://seaborn.pydata.org/examples/layered_bivariate_plot.html |
Line / Time Series
| Example | URL |
|---|---|
| Error Band Lineplots | https://seaborn.pydata.org/examples/errorband_lineplots.html |
| Faceted Lineplot | https://seaborn.pydata.org/examples/faceted_lineplot.html |
| Timeseries Facets | https://seaborn.pydata.org/examples/timeseries_facets.html |
| Wide Data Lineplot | https://seaborn.pydata.org/examples/wide_data_lineplot.html |
Distribution
| Example | URL |
|---|---|
| Faceted Histogram | https://seaborn.pydata.org/examples/faceted_histogram.html |
| Stacked Histogram | https://seaborn.pydata.org/examples/histogram_stacked.html |
| Three Variable Histogram | https://seaborn.pydata.org/examples/three_variable_histogram.html |
| Multiple Conditional KDE | https://seaborn.pydata.org/examples/multiple_conditional_kde.html |
| Multiple ECDF | https://seaborn.pydata.org/examples/multiple_ecdf.html |
| Multiple Bivariate KDE | https://seaborn.pydata.org/examples/multiple_bivariate_kde.html |
Categorical (Box / Violin / Strip / Swarm)
| Example | URL |
|---|---|
| Grouped Barplot | https://seaborn.pydata.org/examples/grouped_barplot.html |
| Grouped Boxplot | https://seaborn.pydata.org/examples/grouped_boxplot.html |
| Horizontal Boxplot | https://seaborn.pydata.org/examples/horizontal_boxplot.html |
| Grouped Violinplots | https://seaborn.pydata.org/examples/grouped_violinplots.html |
| Simple Violinplots | https://seaborn.pydata.org/examples/simple_violinplots.html |
| Jitter Stripplot | https://seaborn.pydata.org/examples/jitter_stripplot.html |
| Scatterplot Categorical (swarm) | https://seaborn.pydata.org/examples/scatterplot_categorical.html |
| Large Distributions (boxenplot) | https://seaborn.pydata.org/examples/large_distributions.html |
| Pointplot ANOVA | https://seaborn.pydata.org/examples/pointplot_anova.html |
| Part-Whole Bars | https://seaborn.pydata.org/examples/part_whole_bars.html |
Joint / Bivariate
| Example | URL |
|---|---|
| Hexbin Marginals | https://seaborn.pydata.org/examples/hexbin_marginals.html |
| Joint Histogram | https://seaborn.pydata.org/examples/joint_histogram.html |
| Joint KDE | https://seaborn.pydata.org/examples/joint_kde.html |
| Marginal Ticks | https://seaborn.pydata.org/examples/marginal_ticks.html |
Pair / Grid / Small Multiples
| Example | URL |
|---|---|
| Scatterplot Matrix | https://seaborn.pydata.org/examples/scatterplot_matrix.html |
| Pair Grid with KDE | https://seaborn.pydata.org/examples/pair_grid_with_kde.html |
| KDE Ridgeplot | https://seaborn.pydata.org/examples/kde_ridgeplot.html |
| Many Facets | https://seaborn.pydata.org/examples/many_facets.html |
Heatmap
| Example | URL |
|---|---|
| Many Pairwise Correlations | https://seaborn.pydata.org/examples/many_pairwise_correlations.html |
| Spreadsheet Heatmap | https://seaborn.pydata.org/examples/spreadsheet_heatmap.html |
| Structured Heatmap (clustermap) | https://seaborn.pydata.org/examples/structured_heatmap.html |
Additional Resources
| Resource | URL |
|---|---|
| seaborn official tutorial | https://seaborn.pydata.org/tutorial.html |
| seaborn API reference | https://seaborn.pydata.org/api.html |
| matplotlib gallery | https://matplotlib.org/stable/gallery/index.html |
| Python Graph Gallery | https://python-graph-gallery.com/ |
Python Visual Data Model
Behavior of dataset and the row cap; traps that cause silent wrong input.
Distinct-row grouping
The 150,000-row cap applies to the deduplicated set, not the raw fact table. Power BI groups the dataset exactly like a table visual before handing it to the script: identical rows across all bound Values columns collapse to one. A script bound to Region, Category over a million-row fact table receives at most as many rows as there are distinct Region + Category combinations.
This is a property of the field bindings, not the script. Consequences:
- Per-transaction charts (jitter, strip, raw scatter, ECDF) silently receive aggregated input if no unique key is bound
- Scripts expecting row-level variation (e.g. bootstrapping, individual observations) produce wrong output without error
- The cap is hit much faster when a unique key is included; pre-filter at the visual or page level first
To force per-row input, bind a guaranteed-unique column to the Values role alongside your other fields:
pbir visuals bind Page/StripPlot -t Column -d "Values:Sales.Region"
pbir visuals bind Page/StripPlot -t Column -d "Values:Sales.Amount"
pbir visuals bind Page/StripPlot -t Column -d "Values:Sales.TransactionKey"Do not use a measure as the unique key; a measure changes the projection kind and does not produce distinct-row expansion. If the model has no natural key, add an index column in Power Query or accept grouped input by design. Verify the effective row count with print(len(dataset)) during development.
Two byte caps the skill header omits:
- Input is capped at 250 MB regardless of row count (Desktop and Service)
- Any single string value over 32,766 chars is silently truncated; validate with
dataset.apply(lambda c: c.str.len().max())before parsing a long bound string
dataset arrives in arbitrary order; sort inside the script, never rely on positional joins.