读出默认的 x 刻度值

问题描述 投票:0回答:1

我想读出默认的 x 刻度值。

在下面的示例中,我想获取默认数组

[1,3,5,7,9,11]
。 我不关心如何计算它,而只想得到最终的 x-ticks 数组。

import plotly.graph_objects as go
import pandas as pd
import plotly.express as px
import json

def save_fig(fig,pngname):
    fig.write_image(pngname,format="png",width=800,height=500, scale=1)
    print("[[%s]]"%pngname)
    return

def main():
    x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    y = [28.8, 28.5, 37, 56.8, 69.7, 79.7, 78.5, 77.8, 74.1, 62.6, 45.3, 39.9]

    fig = go.Figure(go.Scatter(x=x, y=y))
    fig.update_layout(
        xaxis=dict(
            tickmode='linear',
            tick0=1,
            dtick=2
        )
    )
    
    save_fig(fig,"/media/sf_work/demo.png")
    return

main()

输出: enter image description here

python plotly xticks
1个回答
0
投票

您可以通过以下方式获取图形布局信息:

full_fig = fig.full_figure_for_development()

您在该对象中查找的内容似乎是以下字段:

full_fig.layout['xaxis']['tick0']  # first tick value
full_fig.layout['xaxis']['dtick']  # delta tick value
full_fig.layout['xaxis']['range']  # range of x axis

将它们放在一起即可找到图中的刻度标签:

import math

full_fig = fig.full_figure_for_development()
tick0 = full_fig.layout['xaxis']['tick0']
dtick = full_fig.layout['xaxis']['dtick']
rng = full_fig.layout['xaxis']['range']

[i for i in range(tick0, math.floor(rng[1])+1, dtick)]
# -> [1, 3, 5, 7, 9, 11]

相关:如何获取plotly图中生成的x轴和y轴范围?

© www.soinside.com 2019 - 2024. All rights reserved.