你怎么..定义绘图函数



用于数据分析&使用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函数来创建对象fig,该对象是Plotly图形对象。所有图对象(如fig(都有方法add_traceupdate_xaxesupdate_yaxesupdate_layoutshow(以及其他方法(,这些方法可以使用点表示法调用。

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

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

最新更新