My question is very similar to this one, but I still cannot find how to adapt the answers to my problem.
I have a dataframe with 100 columns. I want to use two sliders in Bokeh to select one column to show in the plot. I want to do this with CDSView.
Say the columns are named as such: ["11", "12", .."99"]. Plus I have one column, "x", which is the x axis and does not change. The first slider, range [0-9], should select the first digit of the column name. The second slider should select the last two digits in the same way.
This would mean that if the user selects 2, 5 on the first and second sliders, Bokeh would show a plot using the column "25" from my dataframe.
How can I do this?
So I've found a solution, using some snippets from other questions.
Here is a working example (Bokeh 2+), I hope somebody will find it useful in the future.
import pandas as pd
from bokeh.plotting import figure, show, ColumnDataSource
from bokeh.layouts import column
from bokeh.models import CustomJS, Slider
df = pd.DataFrame([[1,2,3,4,5],[2,20,3,10,20]], columns = ['1','21','22','31','32'])
source_available = ColumnDataSource(df)
source_visible = ColumnDataSource(data = dict(x = df['1'], y = df['21']))
p = figure(title = 'SLIMe')
p.circle('x', 'y', source = source_visible)
slider1 = Slider(title = "SlideME", value = 2, start = 2, end = 3, step = 1)
slider2 = Slider(title = "SlideME2", value = 1, start = 1, end = 2, step = 1)
slider1.js_on_change('value', CustomJS(
args=dict(source_visible=source_visible,
source_available=source_available,
slider1 = slider1,
slider2 = slider2), code="""
var sli1 = slider1.value;
var sli2 = slider2.value;
var data_visible = source_visible.data;
var data_available = source_available.data;
data_visible.y = data_available[sli1.toString() + sli2.toString()];
source_visible.change.emit();
""") )
slider2.js_on_change('value', CustomJS(
args=dict(source_visible=source_visible,
source_available=source_available,
slider1 = slider1,
slider2 = slider2), code="""
var sli1 = slider1.value;
var sli2 = slider2.value;
var data_visible = source_visible.data;
var data_available = source_available.data;
data_visible.y = data_available[sli1.toString() + sli2.toString()];
source_visible.change.emit();
""") )
show(column(p, slider1, slider2))
How can I add "%" next to value in tree view column for below field:
rec.reserved_qty_per = round(rec.sum_reserved_qty / rec.sum_dmd_qty * 100)
when I used to add (+ "%") it's giving me an error that can't mix between float and str fields.
Here's is my Code:
sum_dmd_qty = fields.Float(compute='calculate_dmd_qty', string='Total Ordered Quantity', digits=(12,0))
sum_reserved_qty = fields.Float(compute='calculate_reserved_qty', string='Total Ready Quantity', digits=(12,0))
reserved_qty_per = fields.Float(compute='_compute_percentage', string='Ready (%)', digits=(12,0))
#api.depends('sum_reserved_qty', 'sum_dmd_qty')
def _compute_percentage(self):
for rec in self:
if rec.sum_dmd_qty:
rec.reserved_qty_per = round(rec.sum_reserved_qty / rec.sum_dmd_qty * 100)
The easiest one is to change reserved_qty_per to a Char field.
reserved_qty_per_chr = fields.Char(compute='_compute_percentage', string='Ready (%)')
#api.depends('sum_reserved_qty', 'sum_dmd_qty')
def _compute_percentage(self):
for rec in self:
if rec.sum_dmd_qty:
qty = round(rec.sum_reserved_qty / rec.sum_dmd_qty * 100)
rec.reserved_qty_per = "{0} {1}".format(qty,"%")
In my notebook i have 7 FloatSlider widgets. I want to have the product of these 7 widgets displayed at all times in a way that, as the user moves the sliders, the value displayed is updated. Currently i am trying to display the product of the SliderWidgets in a Widgets.Text (n), but i am not sure if it is the best solution.
import ipywidgets as widgets
caption = widgets.Label(value='Play around with the variables to see how N changes!')
r = widgets.FloatSlider(value=1,
min=1.0,
max=3.0,
step=0.1,
description="R*")
fp = widgets.FloatSlider(value=1,
min=0.35,
max=1.0,
step=0.05,
description="fp")
ne = widgets.FloatSlider(value=1
min=0.2,
max=3.0,
step=0.1,
description="ne")
fl = widgets.FloatSlider(value=1,
min=1.0,
max=1.3,
step=0.05,
description="fl")
fi = widgets.FloatSlider(value=1,
min=0.5,
max=1.5,
step=0.05,
description="fi")
fc = widgets.FloatSlider(value=0.20,
min=0.10,
max=0.30,
step=0.05,
description="fi",)
l = widgets.FloatSlider(value=60000000.0,
min=5000000.0,
max=1000000000.0,
step=5000000,
description="fi")
n = widgets.Text(
value= str(int(r.value * fp.value * ne.value * fl.value * fi.value * fc.value * l.value)) + " civilizations" ,
description='Estimated N:',
disabled=True)
left_box = VBox([r, fp, ne,fl])
right_box = VBox([ fi,fc,l,n])
HBox([left_box, right_box])
This code that i used displays the widgets, but does not update the widget n automatically. What is the best way for me to do it, that does not involve printing a new value everytime?
You can use an observe and a callback function on value change for each slider
def on_value_change(change):
n.value = str(int(r.value * fp.value * ne.value * fl.value * fi.value * fc.value * l.value)) + " civilizations"
r.observe(on_value_change)
fp.observe(on_value_change)
# ...
There are various posts related to infinite loops on here but none reflect my particular predicament (they deal with Java or they do not match my code format etc). The code I have used is actually source code or 'answer code' to an exercise aimed at new students such as myself and it only supplies the 'correct code without correct format' which for an independent student can complicate things but also provide a more productive challenge.
The code makes solid use of 'functions' and 'calling functions from within other functions' which leaves very little 'global code' as a result, this may make things slightly more complicated but hopefully experienced programmers won't be phased by this.
I think the loop is either an issue with my 'while loop code indentation' or the 'while loop condition/counter code itself'. The loop code takes and uses data from other parts of the program code and shouldn't be completely ruled out but realistically I suspect the problem is one of the two former possible issues of either indentation or internal loop code itself, I have already tried multiple variations of 'indentation layout' as well as making quick fixes (misstyped syntax etc).
The code in question can be found towards the end of the program code (there is only one 'while loop' in the program code) it is in the 'menu options' section of code under '# Loop through quotes selecting those referencing the appropriate month and store the data in the summary dictionary'.
I have included two separate code windows, one highlighting the suspected 'problem code' and the the other with 'full program code'. Any help in any aspect will be appreciated.
Code segment most likely to hold error
def monthlyReport():
file = open(QUOTES_TO_DATE_FILE, 'r')
text = file.read()
file.close()
quotes = text.split()
month = input('Enter month: ')
summary = {'Lawn':{'Quantity' : 0.0, 'Value' : 0.0}, 'Patio' :{'Quantity' : 0.0, 'Value' : 0.0}, 'Water Feature' :{'Quantity' : 0.0, 'Value' : 0.0}}
# Loop through quotes selecting those referencing the appropriate month and
#store the data in summary dictionary
index = 0
while True:
if quotes[index] == month:
inputQuotesFromFile2(quotes[index+1])
summary['Lawn']['Quantity'] = summary['Lawn']['Quantity'] + quote['Lawn']['Width'] * quote['Lawn']['Length']
summary['Lawn']['Value'] = summary['Lawn']['Value'] + quote ['Lawn']['Cost']
summary['Patio']['Quantity'] = summary['Patio']['Quantity'] + quote['Patio']['Width'] * quote['Patio']['Length']
summary['Patio']['Value'] = summary['Patio']['Value'] + quote['Patio']['Cost']
summary['Water Feature']['Quantity'] = summary['Water Feature']['Quantity'] + quote['Water Feature']['Quantity']
summary['Water Feature']['Value'] = summary['Water Feature']['Value'] + quote['Water Feature']['Cost']
index = index + 2
if (index >= len(quotes)):
break
totalValue = summary['Lawn']['Value'] + summary['Patio']['Value'] + summary['Water Feature']['Value']
outputSummaryDictionary(summary, month, totalValue)
Full program code
# `Dictionary containing time values (mins) per square metre/ per feature
##lawn:20 patio:20 water feature:60
TIME = {'Lawn': 20, 'Patio': 20, 'Water Feature': 60}
# Constant for labour cost
##16.49
LABOUR_COST = 16.49
# Variable for filename of list of quotes made to date
##quotesToDateFile
QUOTES_TO_DATE_FILE = 'quotesToDateFile.txt'
# 'Global variables'
# A dictionary that stores quote data temporarily, contains sub dicts for each
#material type including keys for length, width, cost, time/quantity,cost, time
quote = {'Lawn':{'Length': 0 , 'Width': 0 , 'Cost': 0.0 , 'Time': 0.0},
'Patio':{'Length': 0 , 'Width': 0, 'Cost': 0.0 , 'Time': 0.0 },
'Water Feature':{'Quantity': 0 , 'Cost': 0.0 , 'Time': 0.0}}
# A dictionary storing material costs of individual items (can be updated)
materialCost = {'Lawn': 15.5, 'Patio': 20.99, 'Water Feature': 150}
# 'Input'
# Function to input material info defined by a length
##create function with named parameter for 'item'
def inputItemDimensions(item):
s = 'Enter length of ' + item + ':'
length = int(input('Enter length of material: '))
s = 'Enter width of ' + item + ':'
width = int(input('Enter width of material: '))
return length, width
# Function to input material info defined by quantity
##create function with named parameter 'item
def inputItemQuantity(item):
s = 'Enter quantity of ' + item + ':'
quantity = int(input('Enter quantity of items: '))
return quantity
# Function for input of area and quantity
def itemInput():
global quote
quote['Lawn']['Length'], quote['Lawn']['Width'] = inputItemDimensions('lawn')
quote['Patio']['Length'], quote['Patio']['Width'] = inputItemDimensions('concrete patio')
quote['Water Feature']['Quantity'] = inputItemQuantity('water feature')
# 'Cost calculation'
# Function to calculate, output to screen, return the material cost and time
#to install a landscape item installed by length and width
def costCalculation1(num, item, length, width, cost, time):
print('[{0}]'.format(num))
print('Length and width of the {0} = {1} x {2}m'.format(item, length, width))
area = length * width
print('Total area of {0} = {1:.2f}m^2'.format(item, area))
print('Cost of {0} per m^2 = £{1:.2f}'.format(item, cost))
totalCost = area * cost
print('Total cost of {0} = £{1}\n'.format(item, totalCost))
totalTime = area * time
return totalCost, totalTime
# Function to calculate, output to screen and return the material cost and time
#to install a landscape item installed by quantity
def costCalculation2(num, item, quantity, cost, time):
print('[{0}]'.format(num))
print('Quantity of {0} = {1} items'.format(item, quantity))
print('Cost of one {0} = £{1:.2f}'.format(item, cost))
totalCost = quantity * cost
print("Total cost of {0} {1} = £{2}\n".format(quantity, item, totalCost))
totalTime = quantity * time
return totalCost, totalTime
# Function to calculate individual costs of items
def calculateItemCosts():
global quote
quote['Lawn']['Cost'], quote['Lawn']['Time'] = costCalculation1('1', 'lawn', quote['Lawn']['Length'], quote['Lawn']['Width'], materialCost['Lawn'], TIME['Lawn'])
quote['Patio']['Cost'], quote['Patio']['Time'] = costCalculation1('2', 'patio', quote['Patio']['Length'], quote['Patio']['Width'], materialCost['Patio'], TIME['Patio'])
quote['Water Feature']['Cost'], quote['Water Feature']['Time'] = costCalculation2('3', 'water features', quote['Water Feature']['Quantity'], materialCost['Water Feature'], TIME['Water Feature'])
# Function to calculate workimg costs and output them
def workingCost():
print('Working costs:')
totalTime = (quote['Lawn']['Time'] + quote['Patio']['Time'] + quote['Water Feature']['Time']) / 60
labourCost = totalTime * LABOUR_COST
print('Total time to complete work = {0} mins'.format(totalTime))
print('Cost of work per hour = £{0}'.format(LABOUR_COST))
print('Total cost of work = £{0}\n'.format(labourCost))
# Calculate total fee payable by customer, output to screen and file
materialCost = quote['Lawn']['Cost'] + quote['Patio']['Cost'] + quote['Water Feature']['Cost']
totalCost = materialCost + labourCost
print('Total cost to pay = £{0}\n'.format(totalCost))
# 'Output functions'
# Output details concerning item
def outputItems():
outputItems1('1', 'Lawn', quote['Lawn'])
outputItems1('2', 'Patio', quote['Patio'])
outputItems2('3', 'Water Feature', quote['Water Feature'])
# Output dimensions and cost for certain item
def outputItems1(num, item, itemDict):
print('[{0}]'.format(num))
print('Length of width of {0} = {1}m x {2}m'.format(item, itemDict['Length'], itemDict['Width']))
print('Total cost of {0} = £{1}'.format(item, itemDict['Cost']))
print('Time to install {0} = {1}mins\n'.format(item, itemDict['Time'] / 60))
# Output quantity and cost for item
def outputItems2(num, item, itemDict):
print('[{0}]'.format(num))
print('Quantity of {0} = {1} items'.format(item, itemDict['Quantity']))
print('Cost of one {0} = £{1:.2f}'.format(item, itemDict['Cost']))
print('Time to install {0} = {1:.2f} hours\n'.format(item, itemDict['Time'] / 60))
# Output material cost dictionary
def outputMaterialCostDictionary():
for key, value in materialCost.items():
print('{0} = {1}'.format(key, value))
print('\n')
# Output summary dictionary
def outputSummaryDictionary(summaryD, month, totalV):
outputSummaryItem1(['Month', month, '', '', ''])
outputSummaryItem1(['Total', '', 'Total', 'Total', 'Total'])
outputSummaryItem1(['Working', 'Item', 'Square metre', 'Number', 'Monthly'])
outputSummaryItem1(['Costs', '', 'Purchased', 'Purchased', 'Value'])
outputSummaryItem2('Lawn', summaryD['Lawn'])
outputSummaryItem2('Patio', summaryD['Patio'])
outputSummaryItem3('Water Feature', summaryD['Water Feature'])
outputSummaryItem4(totalV)
# Output summary dictionary item ver 1
def outputSummaryItem1(sList):
print('|{0:^13}|{1:^13}|{2:^13}|{3:^13}|{4:^13}|'.format(sList[0], sList[1], sList[2], sList[3], sList[4]))
# Output summary dictionary item ver 2
def outputSummaryItem2(name, item):
print('|{0:^13}|{1:^13}|{2:13.2f}|{3:^13}|{4:13.2f}|'.format('', name, item['Quantity'], '', item['Value']))
# Output summary dictionary item ver 3
def outputSummaryItem3(name, item):
print('|{0:^13}|{1:^13}|{2:^13}|{3:13.0f}|{4:13.2f}|'.format('', name, '', item['Quantity'], item['Value']))
# Output summary dictionary item ver 4
def outputSummaryItem4(totalValue):
print('|{0:^13}|{1:^13}|{2:^13}|{3:^13}|{4:13.2f}|'.format('Total', '', '', '', totalValue))
# 'File handling'
# Function to output file
def outputToFile():
filename = input('Enter file name: ')
file = open(filename, 'w')
month = input('Enter month:' )
print('Filename = {0}....Month = {1}\n'.format(filename, month))
file.write('{0}\n'.format(month))
s = '{0} {1} {2} {3}\n'.format(quote['Lawn']['Length'], quote['Lawn']['Width'], quote['Lawn']['Cost'], quote['Lawn']['Time'])
file.write(s)
s = '{0} {1} {2} {3}\n'.format(quote['Patio']['Length'], quote['Patio']['Width'], quote['Patio']['Cost'], quote['Patio']['Time'])
file.write(s)
s = '{0} {1} {2}\n'.format(quote['Water Feature']['Quantity'], quote['Water Feature']['Cost'], quote['Water Feature']['Time'])
file.write(s)
file.close()
# Update quotes to date file
file = open(QUOTES_TO_DATE_FILE, 'a')
s = '{0} {1}\n'.format(month, filename)
file.write(s)
file.close()
# Function to input quote from file where file name is not known
def inputQuoteFromFile1():
filename = input('Enter name for input file: ')
inputQuoteFromFile2(filename)
# Function to input quote from file when file IS known
def inputQuoteFromFile2(filename):
file = open(filename, 'r')
text = file.read()
list1 = text.split()
file.close()
# Process the data (ignore first item which is the month)
##declare 'quote' dict as global (this might mean this code is within function)
global quote
subDictionary = {'Length' : float(list1[1]), 'Width' : float(list1[2]), 'Cost' : float(list1[3]), 'Time' : float(list1[4])}
quote['Lawn'] = subDictionary
subDictionary = {'Length' : float(list1[5]), 'Width' : float(list1[6]), 'Cost' : float(list1[7]), 'Time' : float(list1[8])}
quote['Patio'] = subDictionary
subDictionary = {'Quantity' : float(list1[9]), 'Cost' : float(list1[10]), 'Time' : float(list1[11])}
quote['Water Feature'] = subDictionary
file.close()
# 'Menu options'
# Function to allow preperation of a new quote
def prepareANewQuote():
itemInput()
calculateItemCosts()
workingCost()
outputToFile()
# Function to load new material costs
def loadNewMaterialCosts():
filename = input('Enter filename: ')
file = open(filename, 'r')
text = file.read()
file.close()
newMaterialCosts = text.split()
# Assign costs to material cost dictionary
index = 0
for key in materialCost.keys():
materialCost['Key'] = float(newMaterialCosts['index'])
index = index + 1
# Output new material costs # NOTE MAY NEED TO BE INDENTED FURTHER
outputMaterialCostDictionary()
# Function to view and load existing quote
def viewExistingQuote():
inputQuoteFromFile1()
outputItems()
workingCost()
# Function to generate monthly report summary
def monthlyReport():
file = open(QUOTES_TO_DATE_FILE, 'r')
text = file.read()
file.close()
quotes = text.split()
month = input('Enter month: ')
summary = {'Lawn':{'Quantity' : 0.0, 'Value' : 0.0}, 'Patio' :{'Quantity' : 0.0, 'Value' : 0.0}, 'Water Feature' :{'Quantity' : 0.0, 'Value' : 0.0}}
# Loop through quotes selecting those referencing the appropriate month and
#store the data in summary dictionary
index = 0
while True:
if quotes[index] == month:
inputQuotesFromFile2(quotes[index+1])
summary['Lawn']['Quantity'] = summary['Lawn']['Quantity'] + quote['Lawn']['Width'] * quote['Lawn']['Length']
summary['Lawn']['Value'] = summary['Lawn']['Value'] + quote ['Lawn']['Cost']
summary['Patio']['Quantity'] = summary['Patio']['Quantity'] + quote['Patio']['Width'] * quote['Patio']['Length']
summary['Patio']['Value'] = summary['Patio']['Value'] + quote['Patio']['Cost']
summary['Water Feature']['Quantity'] = summary['Water Feature']['Quantity'] + quote['Water Feature']['Quantity']
summary['Water Feature']['Value'] = summary['Water Feature']['Value'] + quote['Water Feature']['Cost']
index = index + 2
if (index >= len(quotes)):
break
totalValue = summary['Lawn']['Value'] + summary['Patio']['Value'] + summary['Water Feature']['Value']
outputSummaryDictionary(summary, month, totalValue)
# 'Main' (initialisation)
# Top level function
def start():
while True :
print('Select one of following options')
print('(1) Prepare new quote')
print('(2) Load new cost data')
print('(3) Load and view existing quote')
print('(4) Generate monthly report summary')
print('(5) Exit')
selection = int(input())
if selection == 1:
prepareANewQuote()
elif selection == 2:
loadNewMaterialCosts()
elif selection == 3:
viewExistingQuote()
elif selection == 4:
monthlyReport()
elif selection == 5:
quit()
else:
print('Error unrecognised command')
# Start
start()
index never gets modified if quotes[index] does not equal month, so the code will keep checking the same value over and over again and never proceed.
You should unindent that assignment of index by one level. But really this is not an appropriate use of a while loop; you should use for to iterate over quotes:
for quote in quotes:
(Also note there are two while loops in this code; and actually far too much use of global.)
I want to select features and to zoom on them and do all these steps using PyQgis.
And I'm able to do both of them separatly but it doesn't seems to work when I try to mix the two of them.
Both of the codes I use for them are from the internet. Here's what I use to select features of a layer :
from qgis.core import *
import qgis.utils
lyrMap = QgsVectorLayer('C:/someplace', 'MapName', 'ogr')
QgsMapLayerRegistry.instance().addMapLayer(lyrMap)
expr = QgsExpression("'Attribute' IS NOT NULL")
it = lyrMap.getFeatures(QgsFeatureRequest(expr))
ids = [i.id() for i in it] #select only the features for which the expression is true
lyrMap.setSelectedFeatures(ids)
And it seems to do the trick as features appear selected on QGis.
In order to zoom the code is much more simple, it's just :
canvas = qgis.utils.iface.mapCanvas()
canvas.zoomToSelected(lyrMap)
But it seems that canvas doesn't consider that there's a selection on lyrMap and simply do nothing. I've tried to do the selection manually in QGis, and then zoom using zoomToSelected, and it worked.
But my objective is to do it without needing to do the selection manually...
Note : I don't think that's the issue, but the attribute I'm doing the selection on is from a join between lyrMap and another layer (I didn't put the code here because I don't think it's linked).
Thanks in advances for answers, clues or anything really :) !
This is working for my plugin. I am using python 2.7 and QGIS 1.8 and 2.0.1.You can use this code after including using vector file and adding it to the registry.
self.rubberBand = None
#create vertex marker for point..older versons..
self.vMarker = None
#add rubberbands
self.crossRb = QgsRubberBand(iface.mapCanvas(),QGis.Line)
self.crossRb.setColor(Qt.black)
def pan(self):
print "pan button clicked!"
x = self.dlg.ui.mTxtX.text()
y = self.dlg.ui.mTxtY.text()
if not x:
return
if not y:
return
print x + "," + y
canvas = self.canvas
currExt = canvas.extent()
canvasCenter = currExt.center()
dx = float(x) - canvasCenter.x()
dy = float(y) - canvasCenter.y()
xMin = currExt.xMinimum() + dx
xMax = currExt.xMaximum() + dx
yMin = currExt.yMinimum() + dy
yMax = currExt.yMaximum() + dy
newRect = QgsRectangle(xMin,yMin,xMax,yMax)
canvas.setExtent(newRect)
pt = QgsPoint(float(x),float(y))
self.zoom(pt)
canvas.refresh()
def zoom(self,point):
canvas = self.canvas
currExt = canvas.extent()
leftPt = QgsPoint(currExt.xMinimum(),point.y())
rightPt = QgsPoint(currExt.xMaximum(),point.y())
topPt = QgsPoint(point.x(),currExt.yMaximum())
bottomPt = QgsPoint(point.x(),currExt.yMinimum())
horizLine = QgsGeometry.fromPolyline( [ leftPt , rightPt ] )
vertLine = QgsGeometry.fromPolyline( [ topPt , bottomPt ] )
self.crossRb.reset(QGis.Line)
self.crossRb.addGeometry(horizLine,None)
self.crossRb.addGeometry(vertLine,None)
if QGis.QGIS_VERSION_INT >= 10900:
rb = self.rubberBand
rb.reset(QGis.Point)
rb.addPoint(point)
else:
self.vMarker = QgsVertexMarker(self.canvas)
self.vMarker.setIconSize(10)
self.vMarker.setCenter(point)
self.vMarker.show()
# wait .5 seconds to simulate a flashing effect
QTimer.singleShot(500,self.resetRubberbands)
def resetRubberbands(self):
print "resetting rubberbands.."
canvas = self.canvas
if QGis.QGIS_VERSION_INT >= 10900:
self.rubberBand.reset()
else:
self.vMarker.hide()
canvas.scene().removeItem(self.vMarker)
self.crossRb.reset()
print "completed resetting.."