如何在Python Plotly中更改Dash图形的大小?

如何在Python Plotly中更改Dash图形的大小?

Plotly支持两个不同的库“Plotly graphs in a Dash app”和“Plotly Graph objects in Plotly Express”。Dash是一个Python框架,用于创建交互式的基于Web的仪表板应用程序。dash库将所有所需的库添加到基于Web的仪表板应用程序中。

导入 dash 核心组件和html组件。添加 plotly.express 方法生成图形。使用 Dcc.Graph() 方法设置高度和宽度坐标的样式。

在本教程中,我们将展示如何在单个浏览器页面上将多个图形添加到Plotly Dash应用中。请按照下面给出的步骤生成单个页面上的Dash应用程序。

步骤1

导入Dash库。

import dash

步骤2

导入Dash核心组件 dcchtml

from dash import dcc, html

步骤3

使用以下模块导入dash依赖项 −

from dash.dependencies import Input, Output

步骤4

导入 plotly.express 模块并别名为 px

import plotly.express as px

步骤5

使用Pandas模块生成数据集。让我们使用以下方法生成数据集,

# 导入Pandas模块
import pandas as pd

df_bar = pd.DataFrame({
   "Season": ["Summer", "Winter", "Autumn", "Spring"],
   "Rating": [3, 2, 1, 4]
})

步骤6

使用以下坐标生成柱状图,并将其存储在 fig 变量中。

fig = px.bar(df_bar, x="Season", y="Rating", barmode="group")

步骤7

创建 main 函数以使用以下命令运行应用程序服务器,

app = dash.Dash(__name__)
if __name__ == '__main__':
   app.run_server(debug=True)

步骤8

html 子元素生成 app布局 ,在div部分中定义如下,

app.layout = html.Div(children=[

   # 从页面顶部元素
   html.Div([html.H1(children='Dash 应用1'),
   html.Div(children='''Dash: 第一个图形.'''),
   dcc.Graph(id='graph1',figure=fig),]),

   # 页面新“行”内的所有元素的新 Div
   html.Div([
      html.H1(children='Dash 应用2'),
      html.Div(children='''Dash: 第二个图形.'''),
      dcc.Graph(id='graph2', figure=fig),
   ]),
])

示例

以下是修改 Dash 图形大小的完整代码 −

import dash
from dash import dcc, html
import pandas as pd
import plotly.express as px

app = dash.Dash(__name__)
df_bar = pd.DataFrame({
   "Season": ["夏季", "冬季", "秋季", "春季"],
   "Rating": [3, 2, 1, 4]
})

fig = px.bar(df_bar, x="Season", y="Rating", barmode="group")

# 设置app的html div布局,并设置高度和宽度
app.layout = html.Div(children=[

   # 从页面顶部的所有元素
   html.Div([
      html.H1(children='Dash应用1'),
      html.Div(children='''
         Dash: 第一张图。
      '''),

      dcc.Graph(
         id='graph1',
         figure=fig,
         style={'width': '60vw', 'height': '70vh'}
      ),
   ])
])

if __name__ == '__main__':
   app.run_server(debug=True)

结果

会在控制台上显示如下输出。

Dash is running on http://127.0.0.1:8050/
 * Serving Flask app 'main'
 * Debug mode: on

点击 URL,它将在浏览器上显示以下输出 −

如何在Python Plotly中更改Dash图形的大小?

注意如何在 dcc.Graph() 中使用 style 属性改变Dash图表的大小。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程