เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การแบ่งหน้าในตารางสถิติสำคัญ

ตารางสถิติสำคัญที่สร้างในบทเรียนก่อนหน้านี้เป็นส่วนเสริมที่ดีสำหรับชุดเครื่องมือวิเคราะห์ของบริษัทอีคอมเมิร์ซระดับโลก แต่ตารางนั้นยาวเกินไป!

มาแก้ปัญหานี้ด้วยตัวเลือกการแบ่งหน้าในตัวของ Dash AG Grid กัน ซึ่งจะช่วยเพิ่มความสะดวกในการใช้งานแอปและให้ผู้ใช้สำรวจข้อมูลในส่วนต่าง ๆ ได้ตามต้องการ

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การสร้างแดชบอร์ดด้วย Dash และ Plotly

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้างออบเจ็กต์ Dash AG Grid ชื่อ grid โดยใช้ฟังก์ชัน AgGrid ใต้บรรทัดที่ 21
  • เปิดใช้งานการแบ่งหน้าสำหรับ grid โดยตั้งค่าพารามิเตอร์ pagination ใต้บรรทัดที่ 25
  • จำกัดแต่ละหน้าให้แสดง 7 แถว โดยตั้งค่าพารามิเตอร์ paginationPageSize ใต้บรรทัดที่ 28

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

from dash import Dash, dcc, html, Input, Output, callback
import plotly.express as px
import pandas as pd
from dash_ag_grid import AgGrid
ecom_sales = pd.read_csv('/usr/local/share/datasets/ecom_sales.csv')
logo_link = 'https://assets.datacamp.com/production/repositories/5893/datasets/fdbe0accd2581a0c505dab4b29ebb66cf72a1803/e-comlogo.png'
key_stats_tb = ecom_sales.groupby(['Country','Major Category', 'Minor Category'])['OrderValue'].agg(['sum', 'count', 'mean']).reset_index().rename(columns={'count':'Sales Volume', 'sum':'Total Sales ($)', 'mean':'Average Order Value ($)'})

money_fmt = {
  "function": (
    """params.value.toLocaleString(
    'en-US', {style: 'currency', currency: 'USD'})""")}

column_defs = [
  {"field": "Major Category"},
  {"field": "Total Sales ($)", "valueFormatter": money_fmt},
  {"field": "Average Order Value ($)", "valueFormatter": money_fmt},
  {"field": "Sales Volume"}
]

# Create a grid
grid = ____(
  columnDefs=column_defs,
  rowData=key_stats_tb.to_dict("records"),
  # Turn on pagination
  dashGridOptions={
    "____": ____,        
    # Show 7 rows per page
    "____": ____}
)

app = Dash()
app.layout = [
  html.Img(src=logo_link, style={'margin':'30px 0px 0px 0px'}),
  html.H1('Sales Aggregations'),
  html.Div([
    html.H2('Key Aggregations'),
    grid],
    style={'width':'850px', 'height':'750px', 'margin':'0 auto'})
]

if __name__ == '__main__':
    app.run(debug=True)
แก้ไขและรันโค้ด