Slider won't change value in VPython - graphics

My slider won't change the value of the parameter I give it. The slider moves, but the value doesn't change. Of import here is 'temperature' which I need to vary with slider 2.
Also, winsound won't play anything and my sliders aren't labeled. What the heck is going on here?
import winsound
import pygame
import time
from visual.controls import *
from visual.graph import *
from math import *
temperature = 50
funct1 = gcurve(color=(temperature*0.04, (temperature*0.04)-2, (temperature*0.04)-2))
for x in arange (0., 100.1, 0.1):
funct1.plot(pos=(x,5.*cos(2.*x)))
def setdir(direction):
cube.dir = direction
def setrate(obj): # called on slider drag events
cuberate(obj.value) # value is min-max slider position
def cuberate(value):
cube.dtheta = 2*value*pi/1e3
def woosh(sound):
winsound.playsound('%s.wav' % sound, winsound.sphere.wav)
x=0
y=0
z=0
w = 350
display(x=w, y=0, width=w, height=w, range=1.5, forward=-vector(0,0,1), newzoom=1)
c = controls(x=0, y=0, width=w, height=w, range=60)
ctrl = slider(pos=(-50,20), width=7, length=100, axis=(1,0,0), text='Temperature', min=0., max=100., value=temperature)
s1 = slider(pos=(-50,40), width=7, length=100, axis=(1,0,0), text='Angular Velocity', action=lambda: setrate(s1))
cube = sphere(color=(temperature*0.04, (temperature*0.04)-2, (temperature*0.04)-2), material=materials.rough, pos=(x,y,z))
sphere.velocity = vector(x,y,z)
setrate(s1)
setdir(-1)
side = .4
thk = 0.3
t=0
dt=0.1
while True:
rate(100)
cube.p = vector (sin(t*0.02*temperature),sin(t*0.03*temperature),sin(t*0.04*temperature))
cube.rotate(axis=(0,1,0), angle=cube.dir*cube.dtheta)
t = t + dt
cube.pos = cube.p*sin(t*temperature/100)/5
woosh
if not (side > cube.x > -side):
cube.p.x = -cube.p.x
if not (side > cube.y > -side):
cube.p.y = -cube.p.y
if not (side > cube.z > -side):
cube.p.z = -cube.p.z

I think it was an oversight of the letter "s" in the word value. Replace value with values ​​in line ctrl:
ctrl = slider(pos=(-50,20), width=7, length=100, axis=(1,0,0), text='temperature', min=0, max=50, values = temperature)

Related

New FigureCanvasTkAgg always keeps a black border

I want to show some figures using tkinter, but new FigureCanvasTkAgg always keeps a black border. For example, I want to build two figures with red borders, but the new one has a black border, just like this:
enter image description here
But when the display window is not active, the black border disappear:
enter image description here
How to solve this problem? Thank you!
Here's the code:
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class display_window:
def __init__(self, width = 1024, height = 768):
self.figure_dict = {}
self.display_level = tk.Tk()
screen_width = self.display_level.winfo_screenwidth()
screen_height = self.display_level.winfo_screenheight()
init_position_x = int((screen_width - width) / 2)
init_position_y = int((screen_height - height) / 2)
position = str(width) + 'x' + str(height) + '+' + str(init_position_x) + '+' + str(init_position_y)
self.display_level.geometry(position)
self.x_offset = 120
self.y_offset = 10
self.figures_interval = 10
new_figure_button = tk.Button(self.display_level, text='new figure', command=self.new_figure_callback)
new_figure_button.place(x=5, y=5)
def new_figure_callback(self):
fig = Figure(figsize=(3, 2), dpi=100)
fig_plot = fig.add_subplot(111)
fig_plot.grid()
figure_canvas = FigureCanvasTkAgg(fig, self.display_level)
figure_widget = figure_canvas.get_tk_widget()
figure_widget.config(highlightthickness = 2, highlightbackground = "red", cursor='cross')
self.figure_dict[figure_widget] = {
"fig": fig,
"fig_plot": fig_plot,
"figure_canvas": figure_canvas,
}
self.arrange_figures(self.x_offset, self.y_offset, self.figures_interval)
def arrange_figures(self, x_offset, y_offset, figures_interval):
figures_area_width = self.display_level.winfo_width() - x_offset - figures_interval
figures_area_height = self.display_level.winfo_height() - y_offset - figures_interval
figure_count = len(self.figure_dict)
figure_width = figures_area_width
figure_height = (figures_area_height - figures_interval * (figure_count - 1)) / figure_count
for i, it in enumerate(self.figure_dict.keys()):
it.config(height = figure_height, width = figure_width)
it.place(x = x_offset, y = y_offset + i * (figure_height + figures_interval))
if __name__ == '__main__':
display_window()
tk.mainloop()
I want all the figures' borders display as in the config function.

What actually happens in this code? I use the Python Turtle library to draw the fireworks, and I try to use random RGB color

import turtle
import random
t = turtle.Turtle()
w = turtle.Turtle()
t.speed(0)
w.speed(0)
w.penup()
t.penup()
def randcolor():
col1 = random.randint(0,255)
col2 = random.randint(0,255)
col3 = random.randint(0,255)
randcol = (col1, col2, col3)
return randcol
def drawfw1(angle):
x = random.randint(0, 100)
y = random.randint(0, 100)
t.goto(x, y)
t.pendown()
for _ in range(random.randint(30,100)):
t.fd(200)
t.left(angle)
t.penup()
def drawfw2(angle):
x = random.randint(0, 100)
y = random.randint(0, 100)
w.goto(x, y)
w.pendown()
for _ in range(random.randint(30,100)):
w.fd(200)
w.left(angle)
w.penup()
while True:
for _ in range(2):
t.pencolor(randcolor())
w.pencolor(randcolor())
angle = random.randint(99,179)
angle2 = random.randint(99,179)
drawfw1(angle)
drawfw2(angle2)
t.clear()
w.clear()
This code is to program the random drawing firework
I actually trying to do something with this, and I know it was right.
But then, the visual studio is not working and the turtle library
also. How can I fix this problems.
This appears to be due to a common turtle color error. Turtle supports two color modes, with the RGB values as integers from 0 - 255 or as floats from 0.0 to 1.0. The float mode is the default. To switch to the other mode, you need to do:
colormode(255)
Below is a simplification of your code with this fix.
from turtle import Screen, Turtle
from random import randrange
def randcolor():
red = randrange(256)
green = randrange(256)
blue = randrange(256)
return (red, green, blue)
def drawfw(angle):
x = randrange(100)
y = randrange(100)
turtle.goto(x, y)
turtle.pendown()
for _ in range(randrange(30, 100)):
turtle.forward(200)
turtle.left(angle)
turtle.penup()
screen = Screen()
screen.colormode(255)
turtle = Turtle()
turtle.speed('fastest')
turtle.penup()
while True:
for _ in range(4):
turtle.pencolor(randcolor())
angle = randrange(99, 180)
drawfw(angle)
turtle.clear()

Python Functions in Classes NameError

I created a class that has different functions that output different graphs. One of the function is to calculate the bid width for whatever variable is being passed. Last night my notebook was running wonderfully but now I'm getting NameError: name 'bin_width' is not defined and I'm not sure why. I tested the bin function in a separate notebook and it works but for some reason it's not working in the class.
Error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-47-1bce9e9c118e> in <module>
2 histo = Graphs('YRONJOB', None, None, None)
3 #Call histogram() function to apply to object
----> 4 histo.histogram()
<ipython-input-46-02e598bef21f> in histogram(self)
42
43 #Create variable that we call the function to calculate the bin width
---> 44 bin = bin_width(self.A)
45 print(bin)
46
NameError: name 'bin_width' is not defined
Can someone please let me know what I'm doing wrong and how to fix the issue. Below I attached my import cell, the first four functions of my class, and the cell where I created the object.
#Import library
import pandas as pd
import math
import numpy as np
import matplotlib.pyplot as plt
#Automatically creates a dataframe don't need pd.DataFrame
data = pd.read_csv("/Users/tianachargin/Desktop/PythonSG/STAT 4490/WidgeOne_CSV.csv")
#print out dataset
print(data)
class Graphs:
#Constructor with parameters
#Self isn't a pass by value parameter but it allows you to reference
def __init__(self, quantVar1, quantVar2, qualVar1, qualVar2):
self.A = quantVar1 #First quantitative variable
self.B = quantVar2 #Second quantitative variable
self.C = qualVar1 #First qualitative variable
self.D = qualVar2 #Second qualitative variable
#Function that calculates bin width for the histogram
def bin_width(variable):
#Import libaray
import math
#Create variable to create array for bins
#Find min of column
min = data[variable].min()
#Find max of column
max = data[variable].max()
#Find the the count of rows (number of data/size/n)
index = data.index
number_of_rows = len(index)
#Calculate number of bins and round up
num_of_bins = (math.ceil(math.sqrt(number_of_rows)))
#Calculate bin width (max - min)/# of bins
bin_width = ((max - min)/num_of_bins)
#Round bin width to one decimal place
increment_bin = round(bin_width, 1)
#Start bin
start_bin = (min - increment_bin)
#End bin
end_bin = (max + increment_bin)
return start_bin, end_bin, increment_bin
#Histogram Function
def histogram(self):
#Import libraries
import math
import numpy as np
import matplotlib.pyplot as plt
#Create variable that we call the function to calculate the bin width
bin = bin_width(self.A)
#Start at value = bin[0], Stop at value = bin[1], Increment by value of bin[2]
bins = np.array(np.arange(start = bin[0], stop = bin[1], step = bin[2]))
#Histogram function
plt.hist(data[self.A], bins, label = self.A, color = "red")
#x-axis label
plt.xlabel(self.A, fontsize = 16)
#y-axis lable
plt.ylabel("Frequency of " + self.A, fontsize = 16)
#Title of graph
plt.title("Histogram of " + self.A, loc = 'center')
plt.show()
return
#Stacked Histogram Function
def stacked_histogram(self):
#Import libraries
import numpy as np
from matplotlib import pyplot as plt
#Create combonations of the values for the two options
data[self.C + "-" + self.D] = data[self.C] + " " + data[self.D]
combos = np.unique(data[self.C + "-" + self.D])
#Create variable that we call the function to calculate the bin width
bin = bin_width(self.A)
#Start at value = bin[0], Stop at value = bin[1], Increment by value of bin[2]
bins = np.array(np.arange(start = bin[0], stop = bin[1], step = bin[2]))
#Create histogram
for i in range(len(combos)):
plt.hist(data[data[self.C + "-" + self.D].isin(combos[i:(len(combos))])][self.A], bins, label = combos[i:(len(combos))])
#x-axis label
plt.xlabel(self.A, fontsize = 16)
#y-axis lable
plt.ylabel("Frequency of ", fontsize = 16)
#Legend of graph
plt.legend(loc = 'upper left')
#Title of graph
plt.title("Histogram of " + self.A + " with unique combinations of " + self.D + " and " + self.C, loc = 'center')
plt.show()
return
#Overlapping Histogram Function
def overlap_histogram(self):
#Import libraries
import numpy as np
from matplotlib import pyplot as plt
#Create variable that we call the function to calculate the bin width
bin = bin_width(self.A)
#Start at value = bin[0], Stop at value = bin[1], Increment by value of bin[2]
bins = np.array(np.arange(start = bin[0], stop = bin[1], step = bin[2]))
#Create histogram
plt.hist(data[self.A], bins, alpha = 0.5, label = self.A, color = "red")
plt.hist(data[self.B], bins, alpha = 0.5, label = self.B, color = "blue")
#x-axis label
plt.xlabel("Variables", fontsize = 16)
#y-axis lable
plt.ylabel("Frequency", fontsize = 16)
#Legend of graph
plt.legend(loc = 'upper left')
#Title of graph
plt.title("Overlapping Histogram of Variables " + self.A + " and " + self.B, loc = 'center')
plt.show()
#Create an object from class Graphs that will have one parameter
histo = Graphs('YRONJOB', None, None, None)
#Call histogram() function to apply to object
histo.histogram()
first thing i want to say is that youre not supposed to import modules in functions. its enough to import them on the top.
Second thing, youre doing
def bin_width(variable)
and using like this
bin_width(self.A)
right way
def bin_width(self, variable)
usage:
bin = bin_width(self, yourvariable)

Mapping pixel value to temperature value on a thermal image

I have a thermal image (with a color bar) from an IR camera. My goal is to get the temperature of any point by clicking on it.
I have already written a script that retrieves the RBG values of any pixel by right-clicking on it.
I figure that using the max and min temperatures of the color bar, I can map pixel values to temperature values.
Is this possible or is there a better way to approach this?
Thank you very much.
from PIL import Image
import cv2
from win32api import GetSystemMetrics
counter = 0
max_value = input('Max Temp Value: ')
min_value = input('Min Temp Value: ')
def mouse_callback(event, x, y, flags, params): # Tracks the pixel the mouse it hovering on. When right click it prints the pixel location and its RBG values.
global counter
if event == 2:
counter += 1
r, g, b = rgb_img.getpixel((x, y))
print(f'{counter}: {[x, y]} value {r} {g} {b}')
else:
print([x, y], end='\t\r', flush=True)
path_image = 'colors.jpg'
img = cv2.imread(path_image)
im = Image.open(path_image)
rgb_img = im.convert('RGB')
width = GetSystemMetrics(0)
height = GetSystemMetrics(1)
scale_width = width / im.size[0]
scale_height = height / im.size[1]
scale = min(scale_width, scale_height)
window_width = int((im.size[0] * scale) * 0.5)
window_height = int((im.size[1] * scale) * 0.5)
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.resizeWindow('image', window_width, window_height)
cv2.setMouseCallback('image', mouse_callback)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

How to change the opacity of chosen scatter plot points

I want to create an interactive scatter plot so the user can select points with the cursor, so the chosen points are highlighted and the rest are faded.
Right now it only works if the color is changed, how can i change the opacity and keep the original colors?
import numpy as np
from numpy.random import rand
from matplotlib.widgets import LassoSelector
from matplotlib.path import Path
import matplotlib.pyplot as plt
class SelectFromCollection(object):
def __init__(self, ax, collection,c, alpha_other=0.3):
self.canvas = ax.figure.canvas
self.collection = collection
self.alpha_other = alpha_other
self.xys = collection.get_offsets()
self.Npts = len(self.xys)
self.c = c
# Ensure that we have separate colors for each object
self.fc = collection.get_facecolors()
if len(self.fc) == 0:
raise ValueError('Collection must have a facecolor')
elif len(self.fc) == 1:
self.fc = np.tile(self.fc, (self.Npts, 1))
self.lasso = LassoSelector(ax, onselect=self.onselect)
self.ind = []
def onselect(self, verts):
path = Path(verts)
self.ind = np.nonzero(path.contains_points(self.xys))[0]
self.fc[:, -1] = self.alpha_other
self.fc[self.ind, -1] = 1
self.collection.set_facecolors(self.fc)
self.canvas.draw_idle()
def disconnect(self):
self.lasso.disconnect_events()
self.fc[:, -1] = 1
self.collection.set_facecolors(self.fc)
self.canvas.draw_idle()
np.random.seed(1)
x, y, c = rand(3, 100)
subplot_kw = dict(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
fig, ax = plt.subplots(subplot_kw=subplot_kw)
pts = ax.scatter(x, y,c=c, s=100)
selector = SelectFromCollection(ax, pts, c)
plt.show()
Solved, I used the method self.collection.get_facecolors(), to get the format and values, then I just changed the value of the 3rd column for the chosen indices like this:
fc = self.collection.get_facecolors()
fc[self.ind, 3] = 1
fc[others, 3] = self.alpha_other
self.collection.set_facecolors(fc)
cheers

Resources