在 MDX 中嵌入可交互的 Plotly 图表

published_on
11 分钟阅读
--- 阅读量

引言

这篇文章收录了一些简短的代码片段,用来通过 iframe 在 MDX 中嵌入可交互的 HTML。

教程部分专门针对基于 tailwind-nextjs-starter-blog(快照)模板搭建的博客,讲解如何在其中使用 Plotly 生成的 HTML 可视化图表。如果你用的不是这个模板,可以看看细节部分,并修改那里更通用的代码片段。

教程

整个过程和模板提供的“创建 MDX 教程”(快照)非常相似。

  1. 在 components 文件夹中新建一个 HTMLPlot.tsx 组件。
展开 / 收起完整代码
HTMLPlot.tsx
'use client'

import React, { useState, useEffect } from 'react'

const HTMLPlot = ({
  title,
  pathname,
  height_before_scale = '433.59',
  width_before_scale = '768',
}) => {
  // Convert string to number, state to store the current plot layout
  const height_numeric = +height_before_scale
  const width_numeric = +width_before_scale
  const [layout, setLayout] = useState({
    width: '762px',
    height: '571.5px',
    scale_change_str: 'scale(0.5291666666666667)',
    shift: '0px',
  })

  let origin = ''

  // Update layout on resize
  const handleResize = () => {
    if (typeof window !== 'undefined') {
      origin = window.location.origin
      console.log(origin.concat(pathname))
    }
    if (window.innerWidth >= 1280) {
      setLayout({
        ...layout,
        width: `${762 + 48 * 2}px`,
        height: `${(762 + 48 * 2) * (height_numeric / width_numeric)}px`,
        scale_change_str: `scale(${(762 + 48 * 2) / width_numeric})`,
        shift: `${-48}px`,
      })
    } else if (window.innerWidth >= 768) {
      setLayout({
        ...layout,
        width: `${672 + 48 * 2}px`,
        height: `${(672 + 48 * 2) * (height_numeric / width_numeric)}px`,
        scale_change_str: `scale(${(672 + 48 * 2) / width_numeric})`,
        shift: `${-48}px`,
      })
    } else {
      setLayout({
        ...layout,
        width: `${window.innerWidth}px`,
        height: `${window.innerWidth * (height_numeric / width_numeric)}px`,
        scale_change_str: `scale(${window.innerWidth / width_numeric})`,
        shift: `${window.innerWidth >= 640 ? -48 : -32}px`,
      })
    }
  }

  // Effect to handle resizing
  useEffect(() => {
    window.addEventListener('resize', handleResize) // Add resize event listener
    handleResize() // Run resize to update plot layout immediately
    return () => {
      window.removeEventListener('resize', handleResize) // Cleanup the event listener
    }
  }, []) // Empty dependency array ensures the effect runs only on mount and unmount

  return (
    <div
      style={{
        overflow: 'hidden',
        position: 'relative',
        width: layout.width,
        height: layout.height,
        marginLeft: layout.shift,
      }}
    >
      <iframe
        title={title}
        src={origin.concat(pathname)}
        style={{
          height: `${height_numeric}px`,
          width: `${width_numeric}px`,
          transform: layout.scale_change_str,
          transformOrigin: '0px 0px',
          border: '0',
        }}
      ></iframe>
    </div>
  )
}

export default HTMLPlot
  1. 把组件添加到 components/MDXComponents.tsx 中。
展开 / 收起完整代码
UpdateMDXComponents.tsx
...
+ import HTMLPlot from './HTMLPlot'

export const components: MDXComponents = {
  Image,
  TOCInline,
  a: CustomLink,
  pre: Pre,
  BlogNewsletterForm,
+  HTMLPlot,
}
  1. 用 Plotly 创建一个可交互的图表,并保存为 HTML。

这里用的是一个简单的例子,由 Plotly 官方文档(快照)中的示例修改而来。如果你没有安装 Python 或相关的包,这段代码应该可以直接在 Google Colab 的新 Notebook 中运行,你可以从屏幕左侧的文件标签页下载输出结果。

展开 / 收起完整代码
InteractivePlot.py
import plotly.graph_objects as go
import numpy as np

# Create figure
fig = go.Figure()

# Add traces, one for each slider step
for step in np.arange(0, 3.1, 0.1):
    fig.add_trace(
        go.Scatter(
            visible=False,
            line=dict(color="#00CED1", width=6),
            name="𝜈 = " + str(step),
            x=np.arange(0, 10, 0.01),
            y=np.sin(step * np.arange(0, 10, 0.01))))

# Make 10th trace visible
fig.data[10].visible = True

# Create and add slider
steps = []
for i in range(len(fig.data)):
    step = dict(
        method="update",
        args=[{"visible": [False] * len(fig.data)},
              {"title": "Slider switched to step: " + str(i)}],  # layout attribute
    )
    step["args"][0]["visible"][i] = True  # Toggle i'th trace to "visible"
    steps.append(step)

sliders = [dict(
    active=10,
    currentvalue={"prefix": "Frequency: "},
    pad={"t": 30},
    steps=steps
)]

# Fix x and y axis
fig.update_layout(
    sliders=sliders,
    yaxis=dict(range=[-1.1, 1.1]),
    xaxis=dict(range=[0, 10])
)

# Save output html to `sample_plot.html`, can change if needed
# Using [full_html=False, include_plotlyjs='cdn'] makes file size smaller
fig.write_html("sample_plot.html", full_html=False, include_plotlyjs='cdn')
  1. 把 HTML 文件放进 public 文件夹,并记下相对路径。

    • 如果 HTML 直接放在 public 下,路径就是 sample_plot.html
    • 如果 HTML 放在 public/blog_data/blog_name 这样的子目录下,路径就是 blog_data/blog_name/sample_plot.html

目标是让这个 HTML 文件可以通过公开的 URL 访问。

  1. 现在可以在 MDX 文件中以 iframe 的形式嵌入这个 HTML 了。title 可以是任意字符串,只要不重复即可。
Blog.mdx
<HTMLPlot
  title="Sample Plot"
  pathname="/blog_data/embedding-interactive-plotly-charts-in-mdx/sample_plot.html"
/>

大功告成!现在你的网站里就嵌入了一个可交互的可视化图表!

细节

第一步是让 HTML 文件可以通过 URL / 网页链接访问。如果使用 tailwind-nextjs-starter-blog(快照)模板,把文件放进 public 文件夹之后,就可以通过 your.domain/filepath 访问它。以我们的情况为例:

文件路径:

/blog_data/embedding-interactive-plotly-charts-in-mdx/sample_plot.html

公开 URL:

https://fengbojun.com/blog_data/embedding-interactive-plotly-charts-in-mdx/sample_plot.html

示例 1:简单的 iframe

有了这个 URL,就可以轻松地把它嵌入 iframe 组件。例如:

<iframe
  title="Sample 1"
  src="https://fengbojun.com/blog_data/embedding-interactive-plotly-charts-in-mdx/sample_plot.html"
  style={{
    height: `300px`,
    width: `300px`,
  }}
></iframe>

成功了!不过问题也立刻显现出来:由于 iframe 尺寸较小,交互图表的布局 / 格式变得不一样了。此外,iframe 的尺寸是写死的,始终不变,所以除非读者的屏幕刚好是完美的大小,否则图表的尺寸就不合适。

示例 2:带 transform 的 iframe

为了解决布局变化的问题,我们使用 transform 属性。本质上,我们先在一个较大的 iframe 中显示图表,得到想要的布局(图例很大时这一点尤为重要),然后再缩放元素,使其适应屏幕:

<iframe
  title="Sample 2"
  src="https://fengbojun.com/blog_data/embedding-interactive-plotly-charts-in-mdx/sample_plot.html"
  style={{
    width: '1000px',
    height: '564.5px',
    transform: 'scale(0.6)',
    transformOrigin: '0px 0px',
  }}
></iframe>

这样效果好多了——我们看到的就是原来的图表,只是缩小了而已。问题在于,iframe 仍然是 564.5px 高、1000px 宽,图表缩小之后就会留下多余的空白。

示例 3:嵌套在 div 中的 iframe

为了只显示图表而不留多余的空白,我们把 iframe 放进一个 div 里,把不需要的部分“裁掉”。

<div
  style={{
    overflow: 'hidden', // crop out the overflowing blank space
    position: 'relative',
    width: '600px', // 1000 * 0.6
    height: '338.7px', // 564.5 * 0.6
  }}
>
  <iframe
    title="Sample 3"
    src="https://fengbojun.com/blog_data/embedding-interactive-plotly-charts-in-mdx/sample_plot.html"
    style={{
      width: '1000px',
      height: '564.5px',
      transform: 'scale(0.6)',
      transformOrigin: '0px 0px',
    }}
  ></iframe>
</div>

如果你用的是标准尺寸的笔记本电脑屏幕,或者再稍小一点,这个图表看起来就很不错了。不过,还有一个核心问题没有解决:图表无法动态适应屏幕大小。

示例 4:结合 React 的 iframe - 动态缩放与获取域名

为了实现动态缩放,我们需要获取屏幕宽度。既然手边就有 React,我们还可以顺便获取源(origin)URL(例如 https://fengbojun.com),这样只需提供 HTML 文件的相对路径就行了。这也让脚本在开发模式下同样可用,因为它能自动识别本地的临时源(例如 http://localhost:3000)。

这段代码使用 React 的 Hook 和状态来跟踪当前的屏幕大小,并在屏幕大小变化时更新数值。此外,我们用 window.location.origin 来获取源。关于 windows.location,可以参考 Sunil Shakya 在 StackOverflow 上的这篇回答(快照),很有帮助:

假设你有这样一个 URL 路径:

http://localhost:4200/landing?query=1#2

那么,你可以像下面这样使用 location 的各个值:

window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"

window.location.search: "?query=1"

把这些结合起来,就得到了这个 MDX 元素的最终版本,然后就可以像教程部分所说的那样,把它嵌入网页:

HTMLPlot.tsx
'use client'

import React, { useState, useEffect } from 'react'

const HTMLPlot = ({
  title,
  pathname,
  height_before_scale = '433.59',
  width_before_scale = '768',
}) => {
  // Convert string to number, state to store the current plot layout
  const height_numeric = +height_before_scale
  const width_numeric = +width_before_scale
  const [layout, setLayout] = useState({
    width: '762px',
    height: '571.5px',
    scale_change_str: 'scale(0.5291666666666667)',
    shift: '0px',
  })

  let origin = ''

  // Update layout on resize
  const handleResize = () => {
    if (typeof window !== 'undefined') {
      origin = window.location.origin
    }
    if (window.innerWidth >= 1280) {
      setLayout({
        ...layout,
        width: `${762 + 48 * 2}px`,
        height: `${(762 + 48 * 2) * (height_numeric / width_numeric)}px`,
        scale_change_str: `scale(${(762 + 48 * 2) / width_numeric})`,
        shift: `${-48}px`,
      })
    } else if (window.innerWidth >= 768) {
      setLayout({
        ...layout,
        width: `${672 + 48 * 2}px`,
        height: `${(672 + 48 * 2) * (height_numeric / width_numeric)}px`,
        scale_change_str: `scale(${(672 + 48 * 2) / width_numeric})`,
        shift: `${-48}px`,
      })
    } else {
      setLayout({
        ...layout,
        width: `${window.innerWidth}px`,
        height: `${window.innerWidth * (height_numeric / width_numeric)}px`,
        scale_change_str: `scale(${window.innerWidth / width_numeric})`,
        shift: `${window.innerWidth >= 640 ? -48 : -32}px`,
      })
    }
  }

  // Effect to handle resizing
  useEffect(() => {
    window.addEventListener('resize', handleResize) // Add resize event listener
    handleResize() // Run resize to update plot layout immediately
    return () => {
      window.removeEventListener('resize', handleResize) // Cleanup the event listener
    }
  }, []) // Empty dependency array ensures the effect runs only on mount and unmount

  return (
    <div
      style={{
        overflow: 'hidden',
        position: 'relative',
        width: layout.width,
        height: layout.height,
        marginLeft: layout.shift,
      }}
    >
      <iframe
        title={title}
        src={origin.concat(pathname)}
        style={{
          height: `${height_numeric}px`,
          width: `${width_numeric}px`,
          transform: layout.scale_change_str,
          transformOrigin: '0px 0px',
          border: '0',
        }}
      ></iframe>
    </div>
  )
}

export default HTMLPlot