【问题标题】:Set up multiple subplots with moving averages using cufflinks and plotly offline使用袖扣设置多个带有移动平均值的子图并离线绘制
【发布时间】:2019-08-26 00:21:27
【问题描述】:

我试图从我的数据框中选择 4 种不同的产品价格,并使用 plotly 袖扣将它们的移动平均线绘制为子图 (2,2)。如果有人能对此提供指导,我将不胜感激。

我尝试绘制如下价格。 我遇到了袖扣技术分析,它允许我以更清晰的方式绘制移动平均线,但是,我不太确定如何应用它。

from plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplot
from plotly import tools
import plotly.graph_objs as go

trace1= go.Scatter(name=',milk', x=df.Date, y=df['milk'])
trace2= go.Scatter(name='soap', x=df.Date, y=df['soap'])
trace3= go.Scatter(name='rice', x=df.Date, y=df['rice'])
trace4= go.Scatter(name='water', x=df.Date, y=df['water'])

fig = tools.make_subplots(rows=2, cols=2, subplot_titles=('milk', 'soap',
                                                      'rice', 'water'))
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 2)
fig.append_trace(trace3, 2, 1)
fig.append_trace(trace4, 2, 2)

fig['layout'].update(height=1000, width=1800, title='supermarket')

plot(fig, filename='supermarket.html')

如果有人能教我如何使用 plotly 袖扣,使用 plotly 离线绘制数据框中选定列的四个移动平均值,我将不胜感激。

【问题讨论】:

  • 欢迎来到论坛!我喜欢你的问题以及你在这里做出了一些真正的努力。但是,如果您能够提供一些示例数据并尝试遵循How do I ask a good question. 上的其他准则,您将大大增加收到答案的机会。当您收到希望有用的答案时,请考虑this

标签: python plotly offline subplot moving-average


【解决方案1】:

在 Jupyter Notebook 中插入以下代码部分,以使用袖扣和离线绘图生成以下绘图:

剧情:

代码:

# imports
import plotly
from plotly import tools
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import numpy as np
from IPython.core.display import display, HTML
import copy
import plotly.graph_objs as go

####### PART 1 - SETUP AND SAMPLE DATA #######
# setup
display(HTML("<style>.container { width:55% !important; } .widget-select > select {background-color: gainsboro;}</style>"))
init_notebook_mode(connected=True)
np.random.seed(123)
cf.set_config_file(theme='pearl')

# Random data using cufflinks
df = cf.datagen.lines().iloc[:,0:4]
df.columns = ['StockA', 'StockB', 'StockC', 'StockD']

####### PART 2 - FUNCTION FOR MOVING AVERAGES #######

# Function for moving averages
def movingAvg(df, win, keepSource):
    """Add moving averages for all columns in a dataframe.

    Arguments: 
    df -- pandas dataframe
    win -- length of movingAvg estimation window
    keepSource -- True or False for keep or drop source data in output dataframe

    """

    df_temp = df.copy()
    # Manage existing column names
    colNames = list(df_temp.columns.values).copy()
    removeNames = colNames.copy()

    i = 0
    for col in colNames:
        # Make new names for movingAvgs
        movingAvgName = colNames[i] + '_MA' #+ str(win)   
        # Add movingAvgs
        df_temp[movingAvgName] = df[col].rolling(window=win).mean()


        i = i + 1

    # Remove estimates with insufficient window length
    df_temp = df_temp.iloc[win:]

    # Remove or keep source data
    if keepSource == False:
        df_temp = df_temp.drop(removeNames,1)
    return df_temp

# Add moving averages to df
windowLength = 10
df = movingAvg(df=df, win=windowLength, keepSource = True)

####### PART 3 -PLOTLY RULES #######
# Structure lines / traces for the plots
# trace 1
trace1 = go.Scatter(
    x=df.index,
    y=df['StockA'],
    name='StockA'
)

trace1_ma = go.Scatter(
    x=df.index,
    y=df['StockA_MA'],
    name='StockA_MA'
)

# trace 2
trace2 = go.Scatter(
    x=df.index,
    y=df['StockB'],
    name='StockB'

)
trace2_ma = go.Scatter(
    x=df.index,
    y=df['StockB_MA'],
    name='StockB_MA'
)

# trace 3
trace3 = go.Scatter(
    x=df.index,
    y=df['StockC'],
    name='StockC'
)

trace3_ma = go.Scatter(
    x=df.index,
    y=df['StockC_MA'],
    name='StockC_MA'
)

# trace 4
trace4 = go.Scatter(
    x=df.index,
    y=df['StockD'],
    name='StockD'
)

trace4_ma = go.Scatter(
    x=df.index,
    y=df['StockD_MA'],
    name='StockD_MA'
)

# Structure traces as datasets
data1 = [trace1, trace1_ma]
data2 = [trace2, trace2_ma]
data3 = [trace3, trace3_ma]
data4 = [trace4, trace4_ma]

# Build figures
fig1 = go.Figure(data=data1)
fig2 = go.Figure(data=data2)
fig3 = go.Figure(data=data3)
fig4 = go.Figure(data=data4)

# Subplots setup and layout
figs = cf.subplots([fig1, fig2, fig3, fig4],shape=(2,2))
figs['layout'].update(height=800, width=1200,
                      title='Stocks with moving averages = '+ str(windowLength))

iplot(figs)

【讨论】:

  • 嗨,vestland 感谢您的回答,我遇到了这个plot.ly/pandas/moving-average,使用的代码是 cf.datagen.lines(1,500).ta_plot(study='sma',periods=[13,21 ,55],title='Simple Moving Averages') ,你知道如何在上面实现以简化代码吗?谢谢
猜你喜欢
  • 2019-08-05
  • 2017-12-25
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 2022-01-22
  • 2021-08-28
  • 2022-01-22
  • 2020-11-26
相关资源
最近更新 更多