Skip to content

Instantly share code, notes, and snippets.

@thomasnield
Created April 28, 2023 17:25
Show Gist options
  • Save thomasnield/7753244aa713c48c33f77b5ceb3896b1 to your computer and use it in GitHub Desktop.
Save thomasnield/7753244aa713c48c33f77b5ceb3896b1 to your computer and use it in GitHub Desktop.
ChatGPT Manim Example 1
%%manim -qk Histogram
"""
PROMPT: Create sample Python code using manim to plot data into a histogram. Use that same data to create a numberline with points beneath it. Then draw a distribution function over the histogram.
"""
from manim import *
import numpy as np
class Histogram(Scene):
def construct(self):
# Define data
data = np.array([0.4, 0.3, 0.6, 0.8, 0.2, 0.1, 0.9, 0.7, 0.5, 0.3])
# Create histogram
hist = HistogramChart(data, x_min=0, x_max=1, bin_width=0.1, height=4)
hist.to_edge(LEFT)
# Animate the scene
self.play(Create(hist))
self.wait()
class HistogramChart(VGroup):
def __init__(self, data, x_min=None, x_max=None, bin_width=None, height=4, **kwargs):
super().__init__(**kwargs)
self.data = data
self.x_min = x_min or min(data)
self.x_max = x_max or max(data)
self.bin_width = bin_width or (self.x_max - self.x_min) / 10
self.height = height
self.bins = np.arange(self.x_min, self.x_max + self.bin_width, self.bin_width)
self.freq, _ = np.histogram(data, bins=self.bins)
self.freq = self.freq / np.sum(self.freq)
self.freq *= self.height / np.max(self.freq)
self.rects = VGroup(*[Rectangle(
height=freq,
width=bin_width,
fill_opacity=0.8,
fill_color=BLUE,
stroke_width=0,
).move_to(self.n2p(self.bins[i] + bin_width / 2, freq)) for i, freq in enumerate(self.freq)])
self.add(self.rects)
def n2p(self, x, y=0):
return self.coords_to_point(x, y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment