# 게시물에 라이브 Matplotlib 차트를 넣으려면 무엇이 필요할까요?

**URL:** https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939
**Category:** Development
**Created:** [9월 24, 2024, 3:33오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939 "2024-09-24T15:33:59Z")
**Posts on this page:** 10
**Page:** 1

<div class="post-metadata">

### Author: ![Alon1](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alon1/32/197167_2.png) [@Alon1](https://meta.discourse.org/u/Alon1)
#### Post date: [9월 24, 2024, 3:33오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/1 "2024-09-24T15:33:59Z")

</div>

대부분의 커뮤니티에서는 범위를 벗어난 이야기일 수 있지만, 우리는 과학적 커뮤니티이며 Python을 사용하고 서로 Discourse를 통해 많은 그래프(Matplotlib)를 공유합니다.

정적인 jpg/png 대신 **인터랙티브** 그래프를 공유할 수 있다면 정말 **훌륭** 할 텐데요.

다음과 같은 예를 생각해 보세요:

```python
import matplotlib.pyplot as plt
import mpld3
import numpy as np

Fs = 4000
f = 100
sample = 200
x = np.arange(sample)
y = np.sin(2 * np.pi * f * x / Fs)
fig, ax = plt.subplots(1,1)
ax.plot(x, y, marker=".")
html_str = mpld3.fig_to_html(fig)
Html_file= open("index.html","w")
Html_file.write(html_str)
Html_file.close()

```

index.html 파일을 열면 위와 같은 그래프가 표시됩니다(다만 **인터랙티브** 하게 동작한다는 점만 다르고요…)

 ![네 개의 파동형 선이 x축(시간)과 y축(변수, 아마도 주파수 또는 다른 형태의 데이터)에绘制된 그래프. (AI 캡션)](https://global.discourse-cdn.com/meta/original/4X/0/0/7/007bf9bf8cfe260640b56260641321697970b989.png)

즉, 우리는 이미 절반은 해낸 셈이죠?  
아마도 html 파일을 업로드하여 어떤 iframe에서 실행되도록 하면 될까요?

---

<div class="post-metadata">

### Author: ![Alteras](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alteras/32/179824_2.png) [@Alteras](https://meta.discourse.org/u/Alteras)
#### Post date: [9월 24, 2024, 4:24오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/2 "2024-09-24T16:24:40Z")

</div>

설명하신 방법은 커스텀 플러그인을 통해 가능할 것입니다. 이 플러그인은 markdown-it 스타일의 플러그인과 HTML을 위한 적절한 객체 저장소를 결합할 수 있습니다. 그러나 사용자가 입력한 코드가 서버 어디에서든 실행되도록 하는 것에 대해 보안 측면에서 주의가 필요합니다. Discourse는 백엔드에서 HTML과 JS를 안전하게 파싱하기 위해 게시물을 정화(sanitize)하는 데 이미 많은 노력을 기울이고 있습니다.

대신 브라우저에 Python 인터프리터를 임베드하여 클라이언트에서 코드를 실행하고 HTML 생성 과정을 완전히 생략하는 방식을 시도해 보시는 것이 더 효과적일 수 있습니다. [JupyterLite](https://jupyterlite.readthedocs.io/en/latest/index.html)를 사용하면 UI를 갖춘 JupyterLab을 브라우저에서 실행할 수 있습니다. 문서에 따르면, [iframe 생성 시 코드를 자동으로 실행](https://jupyterlite.readthedocs.io/en/latest/quickstart/embed-repl.html#auto-execute-code-on-startup)하도록 설정할 수 있습니다. 커스텀 HighlightJS 플러그인을 사용하여 Python 코드 블록에 실행 가능한 버튼을 생성하여 코드를 전달하거나, 자동으로 실행되도록 할 수 있습니다.

즉, 다음과 같은 방식입니다:

1. 사용자가 Python 코드 블록이 포함된 게시물을 봅니다.
2. 사용자가 코드 블록에 마우스를 올리면 브라우저에서 코드를 실행할 수 있는 버튼이 나타납니다.
3. 사용자가 버튼을 클릭하면 코드 아래에 JupyterLite용 iframe이 생성되고, 코드 블록에서 코드가 가져와집니다.

이것은 단순히 JupyterLite로 향하는 iframe을 생성하는 HighlightJS 플러그인일 뿐이므로, 서버 코드가 필요 없이 Theme Component 내에서 모두 구현할 수 있습니다.

> **[Embed a live REPL on a website — JupyterLite 0.9.0-alpha.1 documentation](https://jupyterlite.readthedocs.io/en/latest/quickstart/embed-repl.html)**

참고할 점: JupyterLite는 JupyterLab과 기능이 완전히 동일하지 않다고 설명되어 있으며, ~~패키지 임포트를 처리하는 방식이 어떻게 되는지 확실하지 않으므로 직접 호스팅해야 할 수도 있습니다.~~ JupyterLite는 [Pyodide](https://pyodide.org/en/stable/)를 사용하며 PyPI의 모든 wheel을 지원하므로 문제없이 작동할 것입니다.

---

<div class="post-metadata">

### Author: ![Alon1](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alon1/32/197167_2.png) [@Alon1](https://meta.discourse.org/u/Alon1)
#### Post date: [9월 24, 2024, 4:44오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/3 "2024-09-24T16:44:43Z")

</div>

index.html이 클라이언트 측(디스커스 서버가 아닌 사용자의 브라우저)에서 실행되는 경우 보안 위험이 그렇게 크지 않다고 생각합니다.

또한 mpld3 방식의 장점은 의존성이 없는 단일 파일이라는 점입니다. 원시 Python을 실행하려면 플롯의 원천이 되는 csv 파일, 데이터 파일 등 모든 의존성도 업로드할 수 있어야 합니다.

그럼에도 불구하고, 디스커스 게시물 내에서 원시 Python 스크립트를 실행할 수 있다면 정말 훌륭할 것입니다!

---

<div class="post-metadata">

### Author: ![Alteras](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alteras/32/179824_2.png) [@Alteras](https://meta.discourse.org/u/Alteras)
#### Post date: [9월 24, 2024, 5:11오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/4 "2024-09-24T17:11:13Z")

</div>

아! HTML이 생성되는 방식을 완전히 오해했네요. 사용자가 HTML을 미리 생성한다면, 도메인이 화이트리스트에 등록된 외부 사이트에서 iframe으로 가져오도록 할 수 있습니다.

> [@Supporting iframe embeds from different domains?](https://meta.discourse.org/t/supporting-iframe-embeds-from-different-domains/30930/61?u=alteras):
>
> iframes can now be whitelisted through the allowed iframes Site Setting.

예를 들어, 기본적으로 허용되어야 하는 codepen:

https://codepen.io/gully/embed/BawMGr?default-tab=result

```html
<iframe height="300" width="800" style="width: 100%;" scrolling="no" title="mplD3 example, actually working" src="https://codepen.io/gully/embed/BawMGr?default-tab=result" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true">
  See the Pen <a href="https://codepen.io/gully/pen/BawMGr">
  mplD3 example, actually working</a> by gully (<a href="https://codepen.io/gully">@gully</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>

```

---

<div class="post-metadata">

### Author: ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)
#### Post date: [9월 24, 2024, 8:31오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/5 "2024-09-24T20:31:54Z")

</div>

절대 가능합니다:

 ![This is a screenshot of a programming interface with a Jupyter notebook displaying a line graph and code for an import statement. (Captioned by AI)](https://global.discourse-cdn.com/meta/original/4X/d/a/5/da5d5fb41595b95686f896baff0589324c0683ba.jpeg)

사용자가 많다면 설정 작업 중 일부를 자동화하는 데 도움이 필요할 수 있습니다.

예산이 있다면 도움을 드릴 수 있습니다.

---

<div class="post-metadata">

### Author: ![Alon1](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alon1/32/197167_2.png) [@Alon1](https://meta.discourse.org/u/Alon1)
#### Post date: [9월 25, 2024, 4:51오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/6 "2024-09-25T16:51:26Z")

</div>

정말 멋진데요!  
몇 가지 질문이 있습니다:

1. [ipympl](https://matplotlib.org/ipympl/)과 함께 작동할 것이라고 생각하시나요? (그렇지 않으면 도표가 인터랙티브하지 않아서 전체적인 의미가 사라집니다.)
2. Jupyter를 실행하기 전에 `PYTHONPATH` 환경 변수를 설정할 수 있는 기반 프로젝트 폴더와 함께 작동할 수 있을까요? 이렇게 하면 사용자가 결합된 프로젝트에서 함수와 의존성을 가져올 수 있습니다.

그리고 네, 이것이 합리적이고 실현 가능하며 전체 Discourse 커뮤니티를 위해 오픈 소스로 기여할 수 있다면 예산이 있습니다.

---

<div class="post-metadata">

### Author: ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)
#### Post date: [9월 25, 2024, 4:55오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/7 "2024-09-25T16:55:12Z")

</div>

> [@Alon1](#):
>
> [ipympl](https://matplotlib.org/ipympl/)과 함께 작동할 것이라고 생각하시나요? (그렇지 않으면 도형이 인터랙티브하지 않아서 전체 의미가 무색해지거든요)

아마도 작동할 가능성이 높습니다.

> [@Alon1](#):
>
> Jupyter를 시작하기 전에 `PYTHONPATH` 환경 변수를 설정할 수 있는 기반 프로젝트 폴더와 함께 작동할 수 있을까요? 이렇게 하면 사용자가 결합된 프로젝트에서 함수와 의존성을 가져올 수 있습니다.

협업 환경을 만들 수 있는 방법을 찾을 수 있을 것 같습니다.

편하게 DM을 보내주세요. 통화로 논의해 볼 수 있습니다.

---

<div class="post-metadata">

### Author: ![Alon1](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alon1/32/197167_2.png) [@Alon1](https://meta.discourse.org/u/Alon1)
#### Post date: [9월 26, 2024, 2:53오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/8 "2024-09-26T14:53:14Z")

</div>

@Alteras 감사합니다. 이 솔루션은 정말 직관적이고, “index.heml” 파일을 Discourse에 업로드하는 방법을 찾으면(이것은 .html 업로드를 활성화하기가 쉬우므로) iframe 코드로 서빙할 때 잘 작동합니다. 유일한 문제는 실제로 작동하지 않는다는 것입니다. 그렇게 시도해 보면 iframe에 렌더링되는 대신 index.html이 다운로드됩니다. iframe에 파일을 다운로드하지 않고 표시하도록 알려주는 메타 태그가 있을까요?

---

<div class="post-metadata">

### Author: ![Alteras](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alteras/32/179824_2.png) [@Alteras](https://meta.discourse.org/u/Alteras)
#### Post date: [9월 26, 2024, 11:55오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/9 "2024-09-26T23:55:05Z")

</div>

아, 그렇군요. Discourse는 기본적으로 이미지 외의 첨부 파일에 Content-Disposition을 "attachment"로 설정하여 다운로드 전용으로 처리합니다.

[Inline PDF Previews](https://meta.discourse.org/t/inline-pdf-previews/157649)와 유사한 방법을 사용할 수 있을 것입니다. 이 방법은 동일한 문제를 PDF 업로드에 대해 처리하는 것 같습니다.

> [@인라인 PDF 미리보기](https://meta.discourse.org/t/inline-pdf-previews/157649):
>
> discourse2요약 인라인 PDF 미리보기는 데스크톱 전용 테마 컴포넌트로, PDF 첨부 파일의 미리보기를 생성할 수 있게 해줍니다.eyeglasses미리보기 [Discourse Theme Creator에서 미리보기](https://discourse.theme-creator.io/theme/Discourse/inline-pdf-previews) (데스크톱 전용)hammer_and_wrench레포지토리 링크 [https://github.com/discourse/discourse-pdf-previews](https://github.com/discourse/discourse-pdf-previews)open_bookDiscourse 테마가 처음이신가요? [Discourse 테마 사용 입문가이드](https://meta.discourse.org/t/beginners-guide-to-using-discourse-themes/91966) 이 테마 컴포넌트 설치 기능 전 후 위에서 언급했듯이, 이 컴포넌트는 데스크톱에서만 작동합니다. 모바일에서는 모든 것이 너무 작아 읽기가 매우 어렵기 때문에 미리보기를 표시할 이점이 거의 없습니다. 이 컴포넌트는 PDF를 렌더링하기 위해 브라우저의 네이티브 구현을 사용…

---

<div class="post-metadata">

### Author: ![system](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/system/32/443519_2.png) [@system](https://meta.discourse.org/u/system)
#### Post date: [10월 26, 2024, 11:55오후 UTC](https://meta.discourse.org/t/what-would-it-take-to-put-a-live-matplotlib-figure-in-a-post/327939/10 "2024-10-26T23:55:15Z")

</div>

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
