使用Plotly和Python/Pandas创建具有两个y轴的子图

3
有没有关于如何在Python中为Plotly设置二次Y轴的指南?我正在通过迭代循环来分配坐标轴样式,如下所示:
all_plots = ['plot1','plot2'...'plot20']
fig = tools.make_subplots(rows=nrow, cols=ncol, shared_xaxes=False, shared_yaxes=False, subplot_titles=all_plots)
for i in all_plots:
    fig['layout']['yaxis'+str(j)].update()

如何分配y轴?

如果我的子图包含4行5列,总共有20个子图,则我是否需要假定plotly需要接收奇数和偶数的数字,即:yaxis1yaxis2 用于 plot1

....

yaxis39yaxis40 用于 plot20


还有其他人对如何实现这个有建议吗? - Andreuccio
3个回答

2

这是可能的,但不特别直观。以下是一个示例,在该示例中,我创建了一个2x2的子图,并在位置2,2添加了一个次要y轴。

当您创建子图时,它们会被分配为"y1"、"y2"、"y3"、"y4"的y轴,位于每个子图的左侧。要创建一个次要y轴,您需要使用fig ['layout'] .update来创建新的y轴"y5"、"y6"、"y7"、"y8",与"y1"、"y2"、"y3"、"y4"相对应。因此,右下角的子图将具有y4(右)和y8(左)两个轴。在下面的示例中,我仅为最后一个子图创建了一个次要y轴,但将其扩展到更多/所有的子图相当简单。

需要注意的是,创建次要轴并在trace5中进行分配并不能自动将其放置在正确的轴上。您仍然需要手动使用fig ['data'] [4] .update (yaxis = 'y'+ str(8))将其分配到左轴以相对绘制。

fig = tools.make_subplots(rows=2, cols=2,subplot_titles=('Air Temperature', 'Photon Flux Density',
                                                         'Ground Temps','Water Table & Precip'))


fig['layout']['xaxis1'].update( range=[174, 256])
fig['layout']['xaxis3'].update(title='Day of Year', range=[174, 256])
fig['layout']['yaxis1'].update(title='Degrees C',range=[-5,30])
fig['layout']['yaxis2'].update(title='mmol m<sup>-2</sup> m<sup>-d</sup>', range=[0, 35])
fig['layout']['yaxis3'].update(title='Ground Temps', range=[0, 11])
fig['layout']['yaxis4'].update(title='depth cm', range=[-20, 0])
fig['layout']['yaxis8'].update(title='rainfall cm', range=[0, 1.6])
fig['layout'].update(showlegend=False, title='Climate Conditions')



# In this example, I am only doing it for the last subplot, but if you wanted to do if for all, 
# Just change to range(1,5)

for k in range(4,5):  
    fig['layout'].update({'yaxis{}'.format(k+4): dict(anchor='x'+str(k),
                                                          overlaying='y'+str(k),
                                                          side='right',
                                                         )
                            })

trace1 = go.Scatter(
        y=Daily['AirTC_Avg'],
        x=Daily.index,
        marker = dict(
        size = 10,
        color = 'rgba(160, 0, 0, .8)',),
        error_y=dict(
            type='data',
            array=Daily_Max['AirTC_Avg']-Daily_Min['AirTC_Avg'],
            visible=True,
        color = 'rgba(100, 0, 0, .5)',
        ),
    name = 'Air Temp'
    )

trace2 = go.Bar(
        y=Daily['PPFD']/1000,
        x=Daily.index,
        name='Photon Flux',
        marker=dict(
            color='rgb(180, 180, 0)'
        ),

    yaxis='y2',
)

trace3 = go.Scatter(
        y=Daily['Temp_2_5_1'],
        x=Daily.index,
        name='Soil Temp',
        marker=dict(
            color='rgb(180, 0, 0)'
        ),

    yaxis='y3',
)


trace4 = go.Scatter(
        y=Daily['Table_1']*100,
        x=Daily.index,
        name='Water Table',
        marker=dict(
            color='rgb(0, 0, 180)'
        ),

    yaxis='y4',
)

trace5 = go.Bar(
        y=Daily['Rain']/10,
        x=Daily.index,
        name='Rain',
        marker=dict(
            color='rgb(0, 100, 180)'
        ),

    yaxis='y8',
)

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.append_trace(trace5, 2, 2)


## This part is important!!! you have to manually assing the data to the axis even 
# though you do it when defining trace 5
fig['data'][4].update(yaxis='y'+str(8))
plot(fig, filename='FI_Climate')

1

虽然不是确切的答案,但我认为它可能会有所帮助...

我喜欢使用pandas和cufflinks。以下是一个示例,演示如何在图表上使用辅助y轴绘制来自一个数据框(df)的两组数据。在此示例中,每个轴的数据以不同的格式显示(散点图和条形图)。在此之前,数据已经被排列成列。

import pandas as pd
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode,plot,iplot    

fig1 = df.iplot(kind='scatter', mode='lines+markers', x=['col1', 'col2'],
                y=['col3', 'col4',],
                asFigure=True)
fig2 = df.iplot(kind='bar', x=['col1', 'col2'],
                  y=['col3', 'col4', ],
                  secondary_y=['col5','col6'],asFigure=True)
fig2['data'].extend(fig1['data'])

3
谢谢你提供这个信息,非常有用。 不幸的是,这并没有回答我的主要问题,即如何制作每个子图都有两个y轴的图表。 - Andreuccio

0

命名规范是y,y2,y3... y40,并且您在跟踪字典中引用轴。

因此,您的跟踪应该是这样的...

trace0 = dict(
    x = xvals,
    y = yvals,
    yaxis = 'y'
)
trace1 = dict(
     x = x2vals,
     y = y2vals,
     yaxis = 'y2'
)
....
trace40 = dict(
     x = x40vals,
     y = y40vals,
     yaxis = 'y40'
)

我不确定我的问题是否清晰。如果我按照您的建议操作,每个子图都会有一个y轴,并且我的两个定义的y轴(一个范围为[0,5],另一个为[0,20])会在后续子图中交替出现,而不是同时出现在每个图中。https://plot.ly/~andrea.botti/627.embed - Andreuccio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接