如何更改我的 Dash Graph 的大小?

2022-01-21 00:00:00 python plotly plotly-dash

问题描述

我在 Dash 上的绘图时遇到了布局困难.我使用 Dash 生成的所有绘图似乎都自动调整为非常窄的尺寸,这使得如果没有一些创造性的缩放就很难实际查看数据.

I'm running into layout difficulties with the plots on Dash. All the plots I generate with Dash seem to be auto sized to be very narrow, which makes it hard to actually view the data without some creative zooming.

作为一个例子,当我在我的一个破折号上查看源代码时,它看起来好像计算出主绘图容器(svg-container)的高度为 450 像素,图形本身的高度为 270 像素(看起来在子图中).如果我能制作图表,比如 700 像素,那就太好了.

As an example, when I view the source on one of my dashes, it looks like it computes the height of the main plot container (svg-container) to be 450px and the height of the graph itself to be 270px (looking at the subplots). It would be nice if I could make the graph, say, 700px.

我的问题是:在 Dash 上调整图形尺寸的最佳方法是什么?我的第一个猜测是以某种方式附加样式表,但我不确定适当的 css 选择器将如何或是什么.

My question is: what is the best way to adjust the dimensions of the graphs on Dash? My first guess would be to somehow attach a stylesheet, but I'm not sure how or what the appropriate css selectors would be.

谢谢!


解决方案

一个 Graph 对象包含一个 figure.每个 figure 都有 datalayout 属性.

A Graph object contains a figure. Each figure has data and layout attributes.

您可以在layout中设置height.

dcc.Graph(
    id="my-graph",
    figure={
        "data": [
            {"x": [1, 2, 3], "y": [4, 1, 2], "type": "bar"},
            {"x": [1, 2, 3], "y": [2, 4, 5], "type": "bar"},
        ],
        "layout": {
            "title": "My Dash Graph",
            "height": 700,  # px
        },
    },
)

根据Plotly figure 对象架构,height 必须是大于等于 10 的数字,默认为 450 (px).

According to the Plotly figure object schema, height must be a number greater than or equal to 10, and its default is 450 (px).

请记住,您可以稍后在破折号回调中创建一个 Graph 对象并设置 figure.

Keep in mind that you can create a Graph object and set figure later, in a dash callback.

例如,如果 dcc.Slidervalue 影响 Graphfigure 属性,您将有:

For example, if the value of a dcc.Slider affects the figure attribute of your Graph you will have:

import plotly.graph_objs as go

dcc.Graph(id="my-graph")

@app.callback(
    output=Output("my-graph", "figure"),
    inputs=Input("slider", "value")])
def update_my_graph(value):
    data = go.Data(
        [
            go.Bar(x=[1, 2, 3], y=[4, 1, 2]),
            go.Bar(x=[1, 2, 3], y=[2, 4, 5]),
        ]
    layout = go.Layout(
        title="My Dash Graph",
        height=700
        )
    figure = go.Figure(data=data, layout=layout)
    return figure

相关文章