Power BI: dynamic KPIs in matplotlib chart
Art Tennick
??3 US Patents in BI??technical editor 4 Packt Power BI books??author 20 computer books??Power BI??Analysis Services??Python/R in Power BI??Paginated??MDX DAX SQL Python R TMDL??ex-university SQL lecturer??35 years in BI
Here is the Python (remember to indent the fors and ifs):
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
AdventureWorks = dataset
x = AdventureWorks["Month"]
y1 = AdventureWorks["Units"]
y2 = AdventureWorks["Revenue"]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1, "black", ls = "-", marker = "o")
ax1.set_ylabel("Units", color = "black")
for t1 in ax1.get_yticklabels():
t1.set_color("black")
ax2 = ax1.twinx()
ax2.plot(x, y2, "white", ls = "-", marker = "o")
ax2.set_ylabel("Revenue", color = "white")
for t1 in ax2.get_yticklabels():
t1.set_color("white")
fmt = "${x:,.0f}"
tick = mtick.StrMethodFormatter(fmt)
ax2.yaxis.set_major_formatter(tick)
ax1.set_xticklabels(x, rotation = 70, color = "#202020")
maxx = ""
maxy = 0
for i, t in enumerate(ax1.get_xticklabels()):
line = ax1.lines[0]
x = line.get_xdata()
x = x[i]
line1 = ax2.lines[0]
y = line1.get_ydata(i)
y = y[i]
if y > maxy:
maxy = y
maxx = x
if y > 170000:
plt.annotate("?", (x, y), xytext = (0, 10), textcoords = "offset points", color = "lime", ha = "center", size = 20)
t.set_color("lime")
#for i, t in enumerate(ax1.get_xticklabels()):
# if i in [0, 1, 11]:
# t.set_color("blue")
# if i in [2, 3, 4]:
# t.set_color("green")
# if i in [5, 6, 7]:
# t.set_color("yellow")
# if i in [8, 9, 10]:
# t.set_color("brown")
plt.title("best month: " + maxx + " with " + "${:0,.0f}".format(maxy) + " revenue", color = "lime")
plt.tight_layout()
fig.patch.set_alpha(0.)
ax1.patch.set_alpha(0.)
plt.show()