Curdoc() keeps adding plots, want to replace - python-2.7

I have written a program that creates a graph based on input from a dropdown list. I am using curdoc().add_root() from bokeh to show my graphs on a server as show() does not work. However, whenever I choose a new option, instead of replacing the current graph, it creates one below it. I have tried curdoc().clear() its not working. How do I make this work where it replaces the graph but doesnt delete the dropdown list, because that is what curdoc().clear() is doing? Here's my code:
import csv
import bokeh.plotting
from bokeh.plotting import figure, curdoc
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import MultiSelect
from bokeh.io import output_file, show, vform
from bokeh.layouts import row
from collections import defaultdict
columns = defaultdict(list) # each value in each column is appended to a list
columns1 = defaultdict(list)
with open('my_data.csv') as f:
for row in f:
row = row.strip()# read a row as {column1: value1, column2: value2,...}
row = row.split(',')
columns[row[0]].append(row[1])
columns[row[0]].append(row[2])
columns[row[0]].append(row[3])
columns[row[0]].append(row[4])
columns[row[0]].append(row[5])
with open('my_data1.csv') as f:
for row in f:
row = row.strip()# read a row as {column1: value1, column2: value2,...}
row = row.split(',')
columns1[row[0]].append(row[1])
columns1[row[0]].append(row[2])
columns1[row[0]].append(row[3])
columns1[row[0]].append(row[4])
columns1[row[0]].append(row[5])
from bokeh.layouts import widgetbox
from bokeh.models.widgets import Dropdown
from bokeh.plotting import curdoc
menu = [("NY", "New York"), ("California", "California"), ("Ohio", "Ohio")]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
count = 0
#def function_to_call(attr, old, new):
#print dropdown.value
def myfunc(attr, old, new):
aaa = dropdown.value
xy = (columns[aaa])
xy = [float(i) for i in xy]
myInt = 10000
xy = [x / myInt for x in xy]
print xy
omega = (columns1[aaa])
omega = [float(i) for i in omega]
print omega
import numpy
corr123 = numpy.corrcoef(omega,xy)
print corr123
a = [2004, 2005, 2006, 2007, 2008]
p = figure(tools="pan,box_zoom,reset,save", title="Diabetes and Stats",
x_axis_label='Years', y_axis_label='percents')
# add some renderers
per = "Diabetes% " + aaa
p.line(a, omega, legend=per)
p.circle(a, omega, legend=per, fill_color="white",line_color="green", size=8)
p.line(a, xy, legend="Per Capita Income/10000")
p.circle(a, xy, legend="Per Capita Income/10000", fill_color="red", line_color="red", size=8)
p.legend.location="top_left"
#bokeh.plotting.reset_output
#curdoc().clear()
curdoc().add_root(p)
curdoc().add_root(dropdown)
#bokeh.plotting.reset_output
dropdown.on_change('value', myfunc)
curdoc().add_root(dropdown)

Related

How to represent the data in x and y axis using matplotlib

Here in my program i want to create the month wise dates on x axis label and and another rs data i want to represent on the y axis.can you please help me how to mention my data in matplotlib.
Given below is my sample program:
import matplotlib.pyplot as plt
from matplotlib import style
# line 1 points
x1 = [1,2,3]
y1 = [2,4,1]
# plotting the line 1 points
plt.plot(x1, y1, 'g', label = "line 1",linewidth=10)
plt.title('Two lines on same graph!')
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.legend()
plt.grid(True,color="k")
plt.show()
# xticks(np.arange(12), calendar.month_name[1:13], rotation=20)
i don't want to mention in between the values it is tacking the x and y values i want to mention like in given diagram.
After few edits and your comments. Is this more closer what you are looking for?
import matplotlib.pyplot as plt
import datetime
# line 1 points
val = [1,2,3,2,6]
cust = [2,4,1,6,2]
orders = [3,5,2,7,3]
col = [1,3,4,2,6]
# plotting the line 1 points
fig, ax = plt.subplots()
start_date = datetime.datetime(2019, 07, 01)
dates = []
# Dates based on the measurement count
# See: https://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python
for single_date in (start_date + datetime.timedelta(n) for n in range(len(val))):
dates.append(single_date.strftime('%Y-%m-%d'))
# Values
plt.plot(dates, val, '.',color='g', markersize=12)
plt.plot(dates, val, label='Values', color='g')
# Customers
plt.plot(dates, cust, '.',color='b', markersize=12)
plt.plot(dates, cust, label='Customers',color='b')
# Orders
plt.plot(dates, orders, '.',color='r', markersize=12)
plt.plot(dates, orders, label='Orders',color='r')
# Collection
plt.plot(dates, col, '.',color='black', markersize=12)
plt.plot(dates, col, label='Collection',color='black')
plt.title('Four lines on same graph!')
plt.tick_params(axis='x', rotation=20)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.grid(True,color="k")
plt.legend()
plt.show()

How to reshape a numpy array from (#dim1,#dim2,#channel) to (#channel, #dim1,#dim2)

I have an array with the shape of (#dim1,#dim2,#channel). I want to reshape it to (#channel, #dim1,#dim2).
The plt.reshape(x, (#channel, #dim1,#dim2)) shows me a wrong image.
If you are using the Cifar10 dataset you could use the following code:
import numpy as np
import matplotlib.pyplot as plt
import cPickle
def unpickle(file):
with open(file, 'rb') as fo:
dict = cPickle.load(fo)
return dict
# Read the data
imageDict = unpickle('cifar-10-batches-py/data_batch_2')
imageArray = imageDict['data']
# Now we reshape
imageArray = np.swapaxes(imageArray.reshape(10000,32,32,3,order='F'), 1, 2)
# Get the labels
labels = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']
imageLabels = [labels[i] for i in imageDict['labels']]
# Plot some images
fig, ax = plt.subplots(4,4, figsize=(8,8))
for axIndex in [(i,j) for i in range(4) for j in range(4)]:
index = np.random.randint(0,10000)
ax[axIndex].imshow(imageArray[index], origin='upper')
ax[axIndex].set_title(imageLabels[index])
ax[axIndex].axis('off')
fig.show()
Which gives you:

cannot get response from Bokeh RadioButtonGroup

I am trying to understand how to use interactivity in RadioButtonGroup using Bokeh and CustomJS with a Python function. I have tweaked the example provided at the Bokeh site for plotting y=x^f. Instead of using a slider for the power f, I would like to toggle between two powers, f=0.5 and f=0.2. I have followed the manual and inserted RadioButtonGroup in my code using Jupyter notebook. The buttons are showing and responsive, but I am unable to get any callback response out of toggling the buttons.
Any help will be appreciated.
from math import pi
from bokeh.io import output_file, show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, Slider, TextInput, RadioButtonGroup
from bokeh.plotting import Figure, output_notebook
output_notebook()
x = [x*0.005 for x in range(0, 200)]
y = x
source = ColumnDataSource(data=dict(x=x, y=y))
plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
def callback(source=source, input1=input1, window=None):
data = source.data
m= input1.active
if m==0:
f=.5
else:
f=2
x, y = data['x'], data['y']
for i in range(len(x)):
y[i] = window.Math.pow(x[i], f)
source.trigger('change')
input1 = RadioButtonGroup(labels=["power = .5", "power = 2."], active=0)
input1.button_type="success"
input1.js_on_change('active', CustomJS.from_py_func(callback))
layout = column(input1, plot)
show(layout)
I can not make bokeh.models.RadioButtonGroup generate a callback, but with bokeh.models.RadioGroup I can (I'm using bokeh version 0.12.4 Maybe a newer version facilitates RadioButtonGroup to generate a callback). Also, you are referencing input1 before declaring it. It's not needed as input of your callback function, inside you can use cb_obj. See:
import bokeh
import bokeh.plotting
bokeh.io.output_notebook()
x = [x*0.005 for x in range(0, 200)]
y = x
source = bokeh.models.ColumnDataSource(data=dict(x=x, y=y))
plot = bokeh.plotting.figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
def callback(source=source, window=None):
data = source.data
m = cb_obj.active
if m==0:
f=.5
else:
f=2
x, y = data['x'], data['y']
for i in range(len(x)):
y[i] = window.Math.pow(x[i], f)
source.trigger('change')
input1 = bokeh.models.RadioGroup(labels=["power = .5", "power = 2."],active=0,
callback=bokeh.models.CustomJS.from_py_func(callback))
layout = bokeh.layouts.column(input1, plot)
bokeh.io.show(layout)

Python Tkinter - Get value from mutliple checkboxes

I am creating a Tkinter application where trying to get value from multiple checkboxes. I am able to create the checkboxes but not able to retrieve the value .i.e. checked or not checked checkboxes.
Requirement:
I need to loop through all checkbox variables to identify the checked ones.
import openpyxl
import sys
import pandas as pd
from Tkinter import *
import ttk
import tkFont
reload(sys)
sys.setdefaultencoding('utf8')
top = Tk()
notebook = ttk.Notebook(top)
notebook.grid(row=1, column=0, columnspan=1, sticky=W)
frame1 = ttk.Frame(top)
notebook.add(frame1, text='TAB1')
s = ttk.Style()
s.theme_use('clam')
helv36 = tkFont.Font(family='Helvetica', size=12, weight=tkFont.BOLD)
wb = openpyxl.load_workbook('File',data_only=True)
ws = wb['Sheet1']
mylist = []
mylist1 = []
for col in ws['A']:
mylist.append(col.value)
for col in ws['B']:
mylist1.append(col.value)
mylist = [str(item) for item in mylist]
mylist1 = [str(item) for item in mylist1]
i=2
for name in mylist:
Label(frame1, text="col1",
borderwidth=1,font=helv36).grid(row=1)
Label(frame1, text=name,
borderwidth=1).grid(row=i)
i +=1
i =2
for name in mylist1:
Label(frame1, text="col2",
borderwidth=1,font=helv36).grid(row=1, column=1)
Label(frame1, text=name,
borderwidth=1).grid(row=i,column=1)
val = IntVar()
val = "v" + str(i)
c_val = Checkbutton(frame1, variable=val)
c_val.grid(row=i, column=2,sticky = W)
i +=1
***def chkbox_checked():
#Need to loop to get checked checkboxes***
B200 = Button(frame1, text ="Check", command = chkbox_checked,font=helv36, bg='orange')
B200.grid(row=100)
top.mainloop()
You can associate a BooleanVar to the checkbox and get the value. You can then use set() method to set the default value for the checkbox and get() to get the state of the checkbox. For example:
import tkinter as tk
root=tk.Tk()
c=tk.BooleanVar()
tk.Checkbutton(root,variable=c,command=lambda: print(c.get())).pack()
root.mainloop()
if you want to loop over a number of checkboxes, you can do this:
import tkinter as tk
root=tk.Tk()
c1=tk.BooleanVar()
c2=tk.BooleanVar()
c3=tk.BooleanVar()
c4=tk.BooleanVar()
def get_value():
for c in (c1,c2,c3,c4):
print(c.get())
tk.Checkbutton(root,text='checkbox1',variable=c1,).pack()
tk.Checkbutton(root,text='checkbox2',variable=c2,).pack()
tk.Checkbutton(root,text='checkbox3',variable=c3,).pack()
tk.Checkbutton(root,text='checkbox4',variable=c4,).pack()
tk.Button(root,text='get value',command=get_value).pack()
root.mainloop()

Python 2.7 Interactive Visualisation

I'm a new programmer who has for a few days trying to create a dropdown list whose input then creates a graph.
For my graph, I'm using Bokeh to create a html file graph, plotting per-capita income of a few places as well as it's percentage of Diabetes. However I have been trying to get it to work for 2 weeks now with a dropdown list and I simply cannot make it work.
I can create the file, but only when the user enters the input by typing. How Can I make this work with a person selecting a place from a dropdown list and the file showing that places graph as output. Here's my code.
Edit:
I want the selected value from the dropdown list to be sent as the value aaa to the program. I know I should turn my graph creating part of the program into a function. But how do I get the value of a dropdown list as the variable aaa?
import csv
from bokeh.plotting import figure, curdoc
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import Dropdown
aaa = raw_input("Write State, not Puerto Rico, Hawaii, or DC: ")
from collections import defaultdict
columns = defaultdict(list) # each value in each column is appended to a list
columns1 = defaultdict(list)
with open('my_data.csv') as f:
for row in f:
row = row.strip()# read a row as {column1: value1, column2: value2,...}
row = row.split(',')
columns[row[0]].append(row[1])
columns[row[0]].append(row[2])
columns[row[0]].append(row[3])
columns[row[0]].append(row[4])
columns[row[0]].append(row[5])
xy = (columns[aaa])
xy = [float(i) for i in xy]
myInt = 10000
xy = [x / myInt for x in xy]
print xy
with open('my_data1.csv') as f:
for row in f:
row = row.strip()# read a row as {column1: value1, column2: value2,...}
row = row.split(',')
columns1[row[0]].append(row[1])
columns1[row[0]].append(row[2])
columns1[row[0]].append(row[3])
columns1[row[0]].append(row[4])
columns1[row[0]].append(row[5])
omega = (columns1[aaa])
omega = [float(i) for i in omega]
print omega
import numpy
corr123 = numpy.corrcoef(omega,xy)
print corr123
a = [2004, 2005, 2006, 2007, 2008]
output_file("lines.html")
p = figure(tools="pan,box_zoom,reset,save", title="Diabetes and Stats",
x_axis_label='Years', y_axis_label='percents')
# add some renderers
per = "Diabetes% " + aaa
p.line(a, omega, legend=per)
p.circle(a, omega, legend=per, fill_color="white",line_color="green", size=8)
p.line(a, xy, legend="Per Capita Income/10000")
p.circle(a, xy, legend="Per Capita Income/10000", fill_color="red", line_color="red", size=8)
p.legend.location="top_left"
show(p)