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

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

Plotly支持两个不同的库:“Plotly Dash应用程序中的Plotly图形”和“Plotly Express中的Plotly图形对象”。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模块生成数据集。让我们使用以下方法生成数据集,

# import pandas module
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.layout = html.Div(children=[

   # elements from the top of the page
   html.Div([html.H1(children='Dash app1'),
   html.Div(children='''Dash: First graph.'''),
   dcc.Graph(id='graph1',figure=fig),]),

   # New Div for all elements in the new 'row' of the page
   html.Div([
      html.H1(children='Dash app2'),
      html.Div(children='''Dash: Second graph.'''),
      dcc.Graph(id='graph2', figure=fig),
   ]),
])

示例

这是修改Plotly中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": ["Summer", "Winter", "Autumn", "Spring"],
   "Rating": [3, 2, 1, 4]
})

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

# app layout for html div and set height and width
app.layout = html.Div(children=[

   # All elements from the top of the page
   html.Div([
      html.H1(children='Dash app1'),
      html.Div(children='''
         Dash: First graph.
      '''),

      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图形的大小

观察我们如何使用“style”属性在“dcc.Graph()”中改变Dash图表的大小。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程