Interactive charts

E2B also allows you to create interactive charts with custom styling.

E2B automatically detects charts when executing Python code with runCode() in JavaScript or run_code() in Python. The Python code must include Matplotlib charts.

When a chart is deteted, E2B sends the data of the chart back to the client. You can access the chart in the execution.results array where each item is a Result object with the chart property.

Here's a simple example of bar chart:

import { Sandbox, BarChart } from '@e2b/code-interpreter'

const code = `
import matplotlib.pyplot as plt

# Prepare data
authors = ['Author A', 'Author B', 'Author C', 'Author D']
sales = [100, 200, 300, 400]

# Create and customize the bar chart
plt.figure(figsize=(10, 6))
plt.bar(authors, sales, label='Books Sold', color='blue')
plt.xlabel('Authors')
plt.ylabel('Number of Books Sold')
plt.title('Book Sales by Authors')

# Display the chart
plt.tight_layout()
plt.show()
`

const sandbox = await Sandbox.create()
const result = await sandbox.runCode(code)
const chart = result.results[0].chart as BarChart

console.log('Type:', chart.type)
console.log('Title:', chart.title)
console.log('X Label:', chart.x_label)
console.log('Y Label:', chart.y_label)
console.log('X Unit:', chart.x_unit)
console.log('Y Unit:', chart.y_unit)
console.log('Elements:', chart.elements)

The code above will output the following:

Terminal
Type: bar
Title: Book Sales by Authors
X Label: Authors
Y Label: Number of Books Sold
X Unit: null
Y Unit: null
Elements: [
  {
    label: "Author A",
    group: "Books Sold",
    value: 100,
  }, {
    label: "Author B",
    group: "Books Sold",
    value: 200,
  }, {
    label: "Author C",
    group: "Books Sold",
    value: 300,
  }, {
    label: "Author D",
    group: "Books Sold",
    value: 400,
  }
]

You can send this data to your frontend to create an interactive chart with your favorite charting library.


Supported intertactive charts

The following charts are currently supported:

  • Line chart
  • Bar chart
  • Scatter plot
  • Pie chart
  • Box and whisker plot