你如何...定义绘图函数

How do you... Define a Graphing Function

用于数据分析并使用 Python。我遇到了这段代码(如下),我的问题是......用户是否从某处复制并粘贴了它,或者我是否从头开始定义了一个绘图函数???????

使用plotly(第一次使用plotly)

对Python很陌生

def make_graph(stock_data, revenue_data, stock):
    fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3)
    fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data.Date, infer_datetime_format=True), y=stock_data.Close.astype("float"), name="Share Price"), row=1, col=1)
    fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data.Date, infer_datetime_format=True), y=revenue_data.Revenue.astype("float"), name="Revenue"), row=2, col=1)
    fig.update_xaxes(title_text="Date", row=1, col=1)
    fig.update_xaxes(title_text="Date", row=2, col=1)
    fig.update_yaxes(title_text="Price ($US)", row=1, col=1)
    fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)
    fig.update_layout(showlegend=False,
    height=900,
    title=stock,
    xaxis_rangeslider_visible=True)
    fig.show() 

如果我理解你的问题,你想知道 make_graph 函数中的函数和方法来自哪里 – 一些导入语句可能会为你解决问题:

import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go

def make_graph(stock_data, revenue_data, stock):
    fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3)
    fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data.Date, infer_datetime_format=True), y=stock_data.Close.astype("float"), name="Share Price"), row=1, col=1)
    fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data.Date, infer_datetime_format=True), y=revenue_data.Revenue.astype("float"), name="Revenue"), row=2, col=1)
    fig.update_xaxes(title_text="Date", row=1, col=1)
    fig.update_xaxes(title_text="Date", row=2, col=1)
    fig.update_yaxes(title_text="Price ($US)", row=1, col=1)
    fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)
    fig.update_layout(showlegend=False,
    height=900,
    title=stock,
    xaxis_rangeslider_visible=True)
    fig.show() 

当您调用函数 make_graph 时,它使用 Plotly 库的 make_subplots function to create an object fig which is a Plotly graph object。所有图形对象(例如 fig)都有方法 add_traceupdate_xaxesupdate_yaxesupdate_layoutshow(以及其他方法),可以使用点符号调用。

最后一行 fig.show() 将使用默认渲染器(例如您的浏览器)来显示图形。

您的教科书很可能包含一些调用 make_graph 函数的示例代码。我认为 运行 这个函数并查看输出也可能有助于为您弄清问题。