How to draw line chart and bar chart together? - python-3.x

I want to draw a bar chart and a line chart in a view,But In Qt I don't know how to draw them together.Can someone know how to do? thanks.
The code
import os
os.environ["QT_API"] = "pyside6"
from qtpy.QtCharts import *
from qtpy.QtWidgets import *
from qtpy.QtCore import Qt
class View(QChartView):
def __init__(self):
super().__init__()
s1 = QBarSet("W01")
s1.append(200)
s2 = QBarSet("W02")
s2.append(300)
s3 = QBarSet("W03")
s3.append(150)
series = QBarSeries()
series.append([s1, s2, s3])
self._chart = QChart()
self.setChart(self._chart)
self._chart.setTitle("Demo")
self._chart.setAnimationOptions(QChart.SeriesAnimations)
self._chart.addSeries(series)
cats = QBarCategoryAxis()
cats.append(["W01", "W02", "W03"])
self._chart.addAxis(cats, Qt.AlignBottom)
series.attachAxis(cats)
vs = QValueAxis()
vs.setRange(0, 400)
self._chart.addAxis(vs, Qt.AlignLeft)
series.attachAxis(vs)
# line series
line_s = QLineSeries()
### how to set x position as a label is a problem?
line_s.append(0 , 140)
line_s.append(1, 200)
line_s.append(3, 450)
line_s.setPointsVisible(True)
self._chart.addSeries(line_s)
app = QApplication()
view = View()
view.show()
app.exec()
Result
That is not I wanted, I wanted like bellow
So how can I re-write my demo code will be like this?

Related

Get pixel color on screen

How to use Jython (Robot) to get a pixel color in R,G,B format and then convert it to HEX.
This is my code so far.
import sys
import os
import java.awt.Robot
import java.awt.Color
def get_pixels(posX, posY):
robot = Robot()
Color = getPixelColor(posX, posY)
r = color.getRed()
g = color.getGreen()
b = color.getBlue()
color = "#{:02x}{:02x}{:02x}".format(r,g,b)
return Color
get_pixels(200, 300)
Well, i found out how to make it work, am gonna share my code anyways.
#Jython
import sys
import os
from java.awt import Robot, Color
def get_pixels(posX, posY):
robot = Robot()
colors = robot.getPixelColor(posX, posY)
r = colors.getRed()
g = colors.getGreen()
b = colors.getBlue()
colors = "#{:02x}{:02x}{:02x}".format(r,g,b)
print (colors)
get_pixels(500, 500)
Thanks, regards!

create list of widgets of n length where n is set by another widget

I want to have the output of the size widget determine the number of widgets created in the output of the return_widgets function. The code below works to a point, but does not update when the value of the intslider changes.
import ipywidgets as widgets
def return_widgets(size):
return [widgets.IntText(value=x) for x in range(size)]
size = widgets.IntSlider(value=3, min=0, max=5, step=1, description='size:')
w = return_widgets(size.value)
widgets.VBox([size, *w])
I did this, not sure it's a very good solution but kind of works:
import ipywidgets as widgets
from IPython.display import display
def return_widgets(size):
return [widgets.IntText(value=x) for x in range(size)]
out = widgets.Output()
def on_value_change(change):
out.clear_output()
with out:
w = return_widgets(change['new'])
display(*w)
size = widgets.IntText(value=3, min=1, max=5, description='size')
size.observe(on_value_change, 'value')
widgets.VBox([size, out])

Making a flashing text in tinker

I want a text that flashes with a clock's seconds. This Link was helpful, but couldn't solve my problem. Below is my little working code:
from tkinter import *
from datetime import datetime
import datetime as dt
import time
def change_color():
curtime=''
newtime = time.strftime('%H:%M:%S')
if newtime != curtime:
curtime = dt.date.today().strftime("%B")[:3]+", "+dt.datetime.now().strftime("%d")+"\n"+newtime
clock.config(text=curtime)
clock.after(200, change_color)
flash_colours=('black', 'red')
for i in range(0, len(flash_colours)):
print("{0}".format(flash_colours[i]))
flashing_text.config(foreground="{0}".format(flash_colours[i]))
root = Tk()
clock = Label(root, text="clock")
clock.pack()
flashing_text = Label(root, text="Flashing text")
flashing_text.pack()
change_color()
root.mainloop()
This line of code: print("{0}".format(flash_colours[i])) prints the alternating colors on the console as the function calls itself every 200s. But the flashing_text Label's text foreground doesn't change colors.
Does anybody have a solution to this problem? Thanks!
Please forgive my bad coding.
Although you have changed the color of the flashing_text in the for loop twice, but the tkinter event handler (mainloop()) can only process the changes when it takes back the control after change_color() completed. So you can only see the flashing_text in red (the last color change).
To achieve the goal, you need to change the color once in the change_color(). Below is a modified change_color():
def change_color(color_idx=0, pasttime=None):
newtime = time.strftime('%H:%M:%S')
if newtime != pasttime:
curtime = dt.date.today().strftime("%B")[:3]+", "+dt.datetime.now().strftime("%d")+"\n"+newtime
clock.config(text=curtime)
flash_colors = ('black', 'red')
flashing_text.config(foreground=flash_colors[color_idx])
clock.after(200, change_color, 1-color_idx, newtime)
I would add it to a class so you can share your variables from each callback.
So something like this.
from tkinter import *
from datetime import datetime
import datetime as dt
import time
class Clock:
def __init__(self, colors):
self.root = Tk()
self.clock = Label(self.root, text="clock")
self.clock.pack()
self.flashing_text = Label(self.root, text="Flashing text")
self.flashing_text.pack()
self.curtime = time.strftime('%H:%M:%S')
self.flash_colours = colors
self.current_colour = 0
self.change_color()
self.root.mainloop()
def change_color(self):
self.newtime = time.strftime('%H:%M:%S')
if self.newtime != self.curtime:
if not self.current_colour:
self.current_colour = 1
else:
self.current_colour = 0
self.curtime = time.strftime('%H:%M:%S')
self.flashing_text.config(foreground="{0}".format(self.flash_colours[self.current_colour]))
self.clock.config(text=self.curtime)
self.clock.after(200, self.change_color)
if __name__ == '__main__':
clock = Clock(('black', 'red'))

prevent camera resetting after plotting with Plotly-python

I am trying to plot some data for a 3d Quiver or Cone using dash and plotly and I want to update the Graph periodically through an interval Input!
So I managed to animate the graph but the problem is that the camera angle and zoom keep resetting after each update.
i have the following code:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Output, Input
import pickle
#reading initial data
with open("shared.pkl", "rb") as f:
quivDic = pickle.load(f)
quiver_3d = go.Cone(x = quivDic["X"], y = quivDic["Y"], z = quivDic["Z"],
u = quivDic["U"], v = quivDic["V"], w = quivDic["W"],
colorscale = 'Blues', name = "testScatter")
data = [quiver_3d]
layout = dict(title ="Test Quiver", showlegend=False, aspectratio=dict(x=1, y=1, z=0.8),
camera_eye=dict(x=1.2, y=1.2, z=0.6))
fig = dict(data=data, layout=layout)
app = dash.Dash()
app.layout = html.Div([
html.Div(html.H4("TEST CONE")),
html.Div(dcc.Graph(id = "testCone", figure=fig)),
dcc.Interval(
id='graph-update',
interval=1000,
n_intervals = 0
),
])
#app.callback(Output('testCone', 'figure'),
[Input('graph-update', 'n_intervals')])
def refresh(n):
#reading new data
with open("shared.pkl", "rb") as f:
quivDic = pickle.load(f)
quiver_3d.x = quivDic["X"]
quiver_3d.y = quivDic["Y"]
quiver_3d.z = quivDic["Z"]
quiver_3d.u = quivDic["U"]
quiver_3d.v = quivDic["V"]
quiver_3d.w = quivDic["W"]
data = [quiver_3d]
#creating new figure
fig = dict(data=data)
return fig
app.run_server(debug=True)
Does anyone know how to avoid this problem?
Ideally I'd like to update the data without redrawing the whole frame, something like "set_data" from matplotlib. Otherwise is there a way to keep track of the latest camera angle and update the layout through the callback?
and Thanks ^^
Yes, you can use the uirevision attribute, as detailed here: https://community.plot.ly/t/preserving-ui-state-like-zoom-in-dcc-graph-with-uirevision/15793

Not able to click 3d objects and move them

I want to click on the loaded models and move them around. I used the code from chess sample examples and panda 3d tutorial without any success. Can someone figure out whats wrong with the code.
Thanks
from math import pi, sin, cos
import sys
from direct.showbase.ShowBase import ShowBase
import direct.directbase.DirectStart
from direct.task import Task
from panda3d.core import TextNode
from direct.gui.OnscreenText import OnscreenText
from panda3d.core import CollisionTraverser, CollisionNode
from panda3d.core import CollisionHandlerQueue, CollisionRay
from panda3d.core import Point3, Vec3, Vec4, BitMask32
from direct.showbase.DirectObject import DirectObject
from panda3d.core import AmbientLight, DirectionalLight, LightAttrib
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# quit when esc is pressed
self.accept('escape', sys.exit)
#base.disableMouse()
# load the box model
self.box = self.loader.loadModel("models/xbox")
self.box.reparentTo(camera)
self.box.setScale(2.0, 2.0, 2.0)
self.box.setPos(8, 50, 0)
self.keyMap = {
"w" :False ,
"s" :False,
"a": False,
"d": False,
"mouse1": False,
"mouse3": False,
}
# CollisionTraverser and a Collision Handler is set up
self.picker = CollisionTraverser()
self.pq = CollisionHandlerQueue()
self.pickerNode = CollisionNode('mouseRay')
self.pickerNP = camera.attachNewNode(self.pickerNode)
self.pickerNode.setFromCollideMask(BitMask32.bit(1))
self.box.setCollideMask(BitMask32.bit(1))
self.pickerRay = CollisionRay()
self.pickerNode.addSolid(self.pickerRay)
self.picker.addCollider(self.pickerNP, self.pq)
self.mouseTask = taskMgr.add(self.mouseTask, 'mouseTask')
self.accept("mouse1", self.setKey, ["mouse1", True])
def mouseTask(self,task):
# check if we have access to the mouse
if base.mouseWatcherNode.hasMouse():
# get the mouse position
mpos = base.mouseWatcherNode.getMouse()
# set the position of the ray based on the mouse position
self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
self.picker.traverse(render)
# if we have hit something sort the hits so that the closest is first and highlight the node
if self.pq.getNumEntries() > 0:
self.pq.sortEntries()
pickedObj = self.picker.getEntry(0).getIntoNodePath()
def setKey(self,key,value):
self.keyMap[key] = value
app = MyApp()
app.run()
I was just trying to do the same thing, when I found your question.
Thanks for your code, it help me to start!
I've manage to get it working :)
Just a remark: you use a task, with no return, this make the task run once.
You should have used: return task.cont
Anyway, here my working code for panda3d devel (1.8.0+):
import sys
from direct.showbase.ShowBase import ShowBase
from pandac.PandaModules import *
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# quit when esc is pressed
self.accept('escape',sys.exit)
#base.disableMouse()
# load the box model
box = self.loader.loadModel("models/box")
box.reparentTo(render)
box.setScale(2.0, 2.0, 2.0)
box.setPos(8, 50, 0)
panda = base.loader.loadModel("models/panda")
panda.reparentTo(render)
panda.setPos(0, 10, 0)
panda.setScale(0.1, 0.1, 0.1)
cNodePanda = panda.attachNewNode(CollisionNode('cnode_panda'))
cNodePanda.node().addSolid(CollisionSphere(0,0,5,5))
cNodePanda.show()
# CollisionTraverser and a Collision Handler is set up
self.picker = CollisionTraverser()
self.picker.showCollisions(render)
self.pq = CollisionHandlerQueue()
self.pickerNode = CollisionNode('mouseRay')
self.pickerNP = camera.attachNewNode(self.pickerNode)
self.pickerNode.setFromCollideMask(BitMask32.bit(1))
box.setCollideMask(BitMask32.bit(1))
panda.setCollideMask(BitMask32.bit(1))
self.pickerRay = CollisionRay()
self.pickerNode.addSolid(self.pickerRay)
self.picker.addCollider(self.pickerNP,self.pq)
self.accept("mouse1",self.mouseClick)
def mouseClick(self):
print('mouse click')
# check if we have access to the mouse
if base.mouseWatcherNode.hasMouse():
# get the mouse position
mpos = base.mouseWatcherNode.getMouse()
# set the position of the ray based on the mouse position
self.pickerRay.setFromLens(base.camNode,mpos.getX(),mpos.getY())
self.picker.traverse(render)
# if we have hit something sort the hits so that the closest is first and highlight the node
if self.pq.getNumEntries() > 0:
self.pq.sortEntries()
pickedObj = self.pq.getEntry(0).getIntoNodePath()
print('click on ' + pickedObj.getName())
app = MyApp()
app.run()

Resources