如何使用def函数创建多个bokeh图

2024-04-19 08:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

有人知道如何在python中使用“def”来创建多个图形吗? 下面是我的代码,我想在选项卡中包含大约20个图表。 如果您在下面的代码上提供帮助,我将不胜感激,因为我不太擅长使用def函数

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]))

#使用def更新到

  • 出现错误:未定义名称“tab1”

  • 这是使用def编码的正确方法吗

  • 你能帮我纠正一下吗

    def图形(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)
    

    图形(df1,'1','tab1')
    图(df2,'2','tab2')

    显示(选项卡(选项卡=[tab1,tab2]))


Tags: fromimportclosedatetimedatetimedefline
1条回答
网友
1楼 · 发布于 2024-04-19 08:23:16

您可以使用def编写函数。函数只是一行python代码,您已经给了它们一个标签,以便可以重用它们

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

因此,您只需编写代码,对一个图形执行此操作,将其全部添加到右边,并为其命名

相关问题 更多 >