Chris Parmer — home

Light curve / transit

Astronomy — Kepler photometry

Example from the compendium of canonical charts

Astronomy — Light curve / transit (Kepler photometry)

Python Code

"""Astronomy — Light curve / transit (Kepler photometry)."""
from pathlib import Path

# ── Palette + theme (matching the Plotly Studio gallery these charts ship in) ──
VIOLET, TEAL, GREEN, PINK, ORANGE = "#845EEE", "#52B3D0", "#55B685", "#DA5597", "#E9A23B"
PRIMARY, SECONDARY = VIOLET, TEAL
COLORWAY = [VIOLET, TEAL, GREEN, PINK, ORANGE]
BG, TEXT, GRID, MUTED = "#ffffff", "#1c2024", "#d9d9e0", "#60646c"
FONT = "Inter, -apple-system, BlinkMacSystemFont, sans-serif"
COLORSCALE = [[0, "rgba(132, 94, 238, 0.05)"], [1, "rgba(132, 94, 238, 0.9)"]]


def apply_theme(fig):
    """Light gallery theme: white background, Inter font, soft gridlines."""
    fig.update_layout(
        paper_bgcolor=BG, plot_bgcolor=BG, colorway=COLORWAY,
        font=dict(family=FONT, color=TEXT, size=12),
        legend=dict(font=dict(color=TEXT)),
        hoverlabel=dict(bgcolor="#f0f0f3", font=dict(color=TEXT, family=FONT), bordercolor=GRID),
    )
    fig.update_xaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)
    fig.update_yaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)


def fetch_csv(url, **kwargs):
    import io
    import pandas as pd
    import requests
    r = requests.get(url, timeout=60)
    r.raise_for_status()
    return pd.read_csv(io.StringIO(r.text), **kwargs)


def fetch_json(url):
    import requests
    r = requests.get(url, timeout=60)
    r.raise_for_status()
    return r.json()

import numpy as np
import pandas as pd
import plotly.graph_objects as go

URL = "https://raw.githubusercontent.com/lightkurve/lightkurve/main/tests/data/ep60021426alldiagnostics.csv"


def generate():
    print("fetching Kepler light curve data …")
    try:
        df = fetch_csv(URL)
        print(f"  columns: {list(df.columns)}")
        # Find time and flux columns
        time_col = None
        flux_col = None
        for c in df.columns:
            cl = c.strip().lower()
            if "bjd" in cl or "time" in cl or "cadence" in cl:
                time_col = c
            if "corrected" in cl and "flux" in cl:
                flux_col = c
        if time_col is None:
            time_col = df.columns[0]
        if flux_col is None:
            for c in df.columns:
                if "flux" in c.lower():
                    flux_col = c
                    break
        if flux_col is None:
            flux_col = df.columns[1]
        print(f"  using time={time_col!r}, flux={flux_col!r}")
        df = df[[time_col, flux_col]].copy()
        df.columns = ["time", "flux"]
        df["flux"] = pd.to_numeric(df["flux"], errors="coerce")
        df["time"] = pd.to_numeric(df["time"], errors="coerce")
        df = df.dropna()
        used_synthetic = False
    except Exception as e:
        print(f"  fetch failed ({e}); generating synthetic Kepler-like light curve")
        used_synthetic = True
        rng = np.random.default_rng(42)
        n = 3000
        time = np.linspace(200, 270, n)
        flux = 1.0 + rng.normal(0, 0.001, n)
        # inject transits with period ~8 days, depth ~0.015
        period = 8.0
        t0 = 204.5
        duration = 0.2
        for k in range(10):
            tc = t0 + k * period
            in_transit = np.abs((time - tc + period / 2) % period - period / 2) < duration / 2
            flux[in_transit] -= 0.015
        df = pd.DataFrame({"time": time, "flux": flux})

    # normalize flux around 1 if it's not already
    median_flux = df["flux"].median()
    if abs(median_flux) > 10:
        df["flux"] = df["flux"] / median_flux

    fig = go.Figure([
        go.Scatter(
            x=df["time"],
            y=df["flux"],
            mode="markers",
            marker=dict(size=5, opacity=0.7, color=VIOLET),
            hovertemplate="t=%{x:.3f}<br>flux=%{y:.5f}<extra></extra>",
        )
    ])
    fig.update_layout(
        xaxis=dict(title="Time (BJD − 2454833)"),
        yaxis=dict(title="Corrected Flux"),
        margin=dict(t=40, b=60, l=70, r=40),
        height=500,
    )
    apply_theme(fig)
    return fig


fig = generate()
fig.show()

Made with Plotly