каким-либо способом ввести динамику c количество «вторичного_у»: Истина в спецификациях make_subplot? - PullRequest
0 голосов
/ 17 июня 2020

основной вопрос: я пытаюсь динамически сгенерировать подзаголовки в plotly- python, используя массив «регионов».

есть ли способ что-то сделать со следующей частью кода, используя мой массив регионов? во фрагменте кода я вручную поместил 4 строки { 'secondary_y':True } ,)

fig = make_subplots(
    rows=1 ,
    cols=len( arr___regions ) ,
    subplot_titles=arr___regions ,
    shared_yaxes=True ,
    specs = [
        [
            { 'secondary_y':True } ,
            { 'secondary_y':True } ,
            { 'secondary_y':True } ,
            { 'secondary_y':True } ,
            ]
        ]
    )

попробовал несколько поисков, но ничего не нашел; не уверен, что я использую правильные условия поиска.

или, может быть, есть некоторые основы о python, которые мне не хватает?

Второй вопрос: shared_yaxes=True разделяет основные оси Y, но вторые Оси Y по-прежнему отображаются на всех подзаголовках. Есть ли у plotly что-нибудь об общих 2-х осях Y?

полный код для обоих вопросов:

import pandas as pd
import plotly.io as pio # https://plotly.com/python/templates/
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from io import StringIO

data_source = StringIO('''region|period|sales|quantity
Central|2014-01|1,539.91|62
Central|2014-02|1,233.17|69
Central|2014-03|5,827.60|123
Central|2014-04|3,712.34|80
Central|2014-05|4,048.51|121
Central|2014-06|9,646.30|158
East|2014-01|436.17|33
East|2014-02|199.78|15
East|2014-03|5,943.39|140
East|2014-04|3,054.91|120
East|2014-05|7,250.10|135
East|2014-06|10,759.16|160
South|2014-01|9,322.09|125
South|2014-02|2,028.99|28
South|2014-03|32,911.12|172
South|2014-04|12,184.61|157
South|2014-05|5,779.24|69
South|2014-06|4,560.25|65
West|2014-01|2,938.72|64
West|2014-02|1,057.96|47
West|2014-03|11,008.90|150
West|2014-04|9,343.49|179
West|2014-05|6,570.44|141
West|2014-06|9,629.42|138
''')

odf = pd.read_csv( data_source , delimiter='|' , thousands=',' , )   # "original dataframe"

pio.templates.default = 'presentation'

arr___regions = pd.unique( odf['region'] )
arr___regions.sort()



fig = make_subplots(
    rows=1 ,
    cols=len( arr___regions ) ,
    subplot_titles=arr___regions ,
    shared_yaxes=True ,
    specs = [
        [
            { 'secondary_y':True } ,
            { 'secondary_y':True } ,
            { 'secondary_y':True } ,
            { 'secondary_y':True } ,
            ]
        ]
    )



sdf = {}   # "sub dataframe"

for idx , region in enumerate( arr___regions , start=0 ):
    sdf[region] = odf[ odf['region'] == region ]

    fig.add_trace(
        go.Bar(
            name='sales',
            x=sdf[region]['period'],
            y=sdf[region]['sales'],
            ) ,
        row=1,col=(idx+1),
        )

    fig.add_trace(
        go.Scatter(
            name='quantity',
            x=sdf[region]['period'],
            y=sdf[region]['quantity'],
            mode='lines+markers',
            line=dict( shape='spline', ) ,
            ) ,
        row=1,col=(idx+1),
        secondary_y=True,
        )



fig.update_xaxes( tickangle=270 , type='category' , )

y_11 = --000
y_12 = 40000
y_21 = y_11*0.010
y_22 = y_12*0.010

fig.update_yaxes(
    title_text='sales',
    range = [ y_11,y_12 ] ,
    )

fig.update_yaxes(
    title_text='quantity',
    secondary_y=True,
    range = [ y_21,y_22 ] ,
    )

fig.update_layout(
    legend_orientation='h' ,
    font = dict( color='#000000' , family='tahoma' , size=10 , ) ,
    margin = dict( l=140,r=140,b=140,t=140,pad=12, ) ,
    )

fig.show()

1 Ответ

0 голосов
/ 17 июня 2020

Что касается вашего основного вопроса, вы можете использовать:

specs = [list([{ 'secondary_y':True }]*len( arr___regions ))]

, чтобы указать соответствующий размер spe c для len( arr___regions )

...