Home > Back-end >  How to add a constant line at (0,0) and two variance/tolerance line to a scatter plot
How to add a constant line at (0,0) and two variance/tolerance line to a scatter plot

Time:09-24

I have a data similar to sample data below in Power BI

import numpy as np
np.random.seed(10)
x = np.arrange(0,100)
y = np.random.randint(0,100,100)

I want to create a scatter plot using the python visual in Power BI and then insert a constant line running from (0,0) and a variance/tolerance line on each axis as shown in the output below: How can I create this visual?

enter image description here

  1. Also is there a way to create a tolerance button that I can use in making the two tolerance lines dynamic? That is if I change to "20" the lines will be drawn from 20 on Y axis and 20 on X axis instead of from 10.

CodePudding user response:

usually that would require a very lengthy program, but since i already had something doing similar functionality, i am just putting it here for people to learn from.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

# define X and y
np.random.seed(10)
x = np.arange(0,100)
y = np.random.randint(0,100,100)

fig = plt.figure(dpi=100,figsize=(8,8))
ax = fig.subplots(1)

p0 = ax.scatter(x,y) # points
p1 = ax.plot([0,100],[0,100],'--',color="grey")  # middle line
p2, = ax.plot([0,90],[10,100],'--',color="black")  # upper line
p3, = ax.plot([10,100],[0,90],'--',color="black")  # lower line
plt.xticks(np.arange(0,101,10))
plt.yticks(np.arange(0,101,10))
plt.grid(True)
plt.xlim([0,100])
plt.ylim([0,100])
plt.subplots_adjust(bottom=0.25)  # reserve the bottom 25% of plot for slider.
ax_slider = plt.axes([0.3,0.1,0.55,0.03])  # make axes for slider

# make slider
win_len = Slider(ax_slider,'Tolerance',valmin=10,valmax=20,valinit=10,valstep=2)
def update(val): # function called whenever slider is updated
    current_v = int(win_len.val)
    p2.set_ydata([current_v,100])
    p2.set_xdata([0,100-current_v])
    p3.set_xdata([current_v,100])
    p3.set_ydata([0,100-current_v])
    fig.canvas.draw()

win_len.on_changed(update) # register slider update function
plt.show() # show the window

the result is close to what you are expecting. see result here

for credit the code was originally adopted from this youtube video , but it is not related to this question.

  • Related