简体   繁体   中英

How to use def function to create mulitple bokeh graphs

does anyone know how to use 'def' in python to create multiple graphs ? My code is below and there are about 20 graphs that I want to include into the tabs. Appreciate if you help below on the code as I not really good in using the def function...

import pandas as pd
from math import pi
from bokeh.plotting import figure,output_file,show
from bokeh.models import ColumnDataSource,NumeralTickFormatter,HoverTool,DaysTicker,DatetimeTickFormatter,TickFormatter,Panel,Tabs
from bokeh.layouts import column,row

#1
# intialise data of lists. 
data1 = {'Date':['2020-10-10', '2020-10-09', '2020-10-08', '2020-10-07', '2020-10-06', '2020-10-05', '2020-10-04', '2020-10-03'], 
        'Close':[20, 21, 19, 18, 30, 10, 15, 18 ] } 

# Create DataFrame 
df1 = pd.DataFrame(data1) 

df1['Date_time']   = pd.to_datetime(df1['Date'], errors='coerce')

p1 = figure(x_axis_type="datetime")
p1.xaxis.major_label_orientation = pi/2
p1.grid.grid_line_alpha=0.8
p1.xaxis[0].ticker.desired_num_ticks = 12
p1.xaxis.formatter=DatetimeTickFormatter(days=['%Y-%m-%d'])
p1.line(df1.Date_time, df1.Close)
tab1 = Panel(child=p1, title="1")


#2
# intialise data of lists. 
data2 = {'Date':['2020-10-10', '2020-10-09', '2020-10-08', '2020-10-07', '2020-10-06', '2020-10-05', '2020-10-04', '2020-10-03'], 
        'Close':[200, 250, 190, 180, 100, 100, 150, 108 ] } 

# Create DataFrame 
df2 = pd.DataFrame(data2) 

df2['Date_time']   = pd.to_datetime(df2['Date'], errors='coerce')

p2 = figure(x_axis_type="datetime")
p2.xaxis.major_label_orientation = pi/2
p2.grid.grid_line_alpha=0.8
p2.xaxis[0].ticker.desired_num_ticks = 12
p2.xaxis.formatter=DatetimeTickFormatter(days=['%Y-%m-%d'])
p2.line(df2.Date_time, df2.Close)
tab2 = Panel(child=p2, title="2")


show(Tabs(tabs=[tab1, tab2]))

#Update to using def

  • I got error: name 'tab1' is not defined

  • Is this the right way to code for using def ?

  • Can you help to correct from here ?

    def graph (y,x,z):

     y['Date_time'] = pd.to_datetime(y['Date'], errors='coerce') p = figure(x_axis_type="datetime") p.line(y.Date_time, y.Close) z = Panel(child=p, title=x)

    graph (df1,'1','tab1')
    graph (df2,'2','tab2')

    show(Tabs(tabs=[tab1, tab2]))

You use def to write functions. Functions are just lines of python code you've given a label to so you can reuse them.

def some_function(x, y):
    # your code here

So you just write the code to do it for one graph, tab it all to the right and give it a name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM