Python Plotly - 对齐散点图和条形图的 Y 轴

Python Plotly - Align Y Axis for Scatter and Bar

我正在尝试创建一个带有散点图和图形元素的绘图图。一切顺利,但有一个问题 - 两个 Y 轴没有在 0 附近对齐。

我试过使用不同的属性,例如 'mirror' 和 tick0,我也尝试按照 plotly 网站上的示例进行操作,但它主要是具有相同图形类型的多个 y-axis。

我该怎么做才能解决这个问题?

import utils
import pandas as pd
import plotly.plotly as py
import plotly.graph_objs as go
import plotly




pd_data ['dt'] = ... dates
pd_data['price'] = ... prices
pd_data['car'] = ... cars

price = go.Scatter(
    x = pd_data['dt'],
    y = pd_data['price'],
    mode = 'lines',
    name = 'Price',
    xaxis = 'x',
    yaxis='y1',     
    marker = dict(
        color = utils.prep_color_string('orange'),
    ),
    line = dict(
        width = utils.line_width,
    ),
)

car = go.Bar(
    x = pd_data['dt'],
    y = pd_data['car'],
    #mode = 'lines',
    name = 'Cars',
    xaxis = 'x',
    yaxis='y2',
    marker = dict(
        color = utils.prep_color_string('light_green'),
    ),
    #line = dict(
    #   width = utils.line_width,
    #),
)

data = [price, car]

layout = dict(

    title = 'Price/Car',

    geo = dict(
        showframe = True,
        showcoastlines = True,
        projection = dict(
            type = 'Mercator'
        )
    ),

    yaxis=dict(
        title = 'Price',
        tickprefix = "$",
        overlaying='y2',
        anchor = 'x'            
    ),

    yaxis2=dict(
        title = 'Car',
        dtick = 1,
        #tickprefix = "",
        side = 'right',
        anchor = 'x',

    ),

)

fig = dict( data=data, layout=layout)
div = plotly.offline.plot( fig, validate=False, output_type = 'file',filename='graph.html' ,auto_open = False)

我也一直在为此苦苦挣扎。完全相同的问题,但我正在使用 R。我想出的方法是对 yaxis 和 yaxis2 布局使用 rangemode="tozero"。

我想你的情况应该是这样的:

layout = dict(

    title = 'Price/Car',

    geo = dict(
        showframe = True,
        showcoastlines = True,
        projection = dict(
            type = 'Mercator'
        )
    ),

    yaxis=dict(
        title = 'Price',
        tickprefix = "$",
        overlaying='y2',
        anchor = 'x',
        rangemode='tozero'            
    ),

    yaxis2=dict(
        title = 'Car',
        dtick = 1,
        #tickprefix = "",
        side = 'right',
        anchor = 'x',
        rangemode = 'tozero'


    ),

)

让我知道这是否适合你。