Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use object-oriented interface for PyPlot not global state #5

Open
fsaad opened this issue Jan 22, 2019 · 0 comments
Open

Use object-oriented interface for PyPlot not global state #5

fsaad opened this issue Jan 22, 2019 · 0 comments

Comments

@fsaad
Copy link
Collaborator

fsaad commented Jan 22, 2019

It's a good habit to encourage users of Gen, especially as they write more complex code for plotting it becomes essential.

Using the object-oriented interface is recommended by the matplotlib documentation (the only reason the non-oo interface exists is for legacy compatibility with MATLAB's poor design). The OO interface is strictly superior in terms of code manageability.

Instead of

function render_trace(trace; show_data=true)
    xs = get_args(trace)[1]
    assmt = get_assmt(trace)
    if show_data
        ys = [assmt[(:y, i)] for i=1:length(xs)]
        scatter(xs, ys, c="black")
    end
    slope = assmt[:slope]
    intercept = assmt[:intercept]
    xmin = minimum(xs)
    xmax = maximum(xs)
    plot([xmin, xmax], slope *  [xmin, xmax] .+ intercept, color="black", alpha=0.5)
    ax = gca()
    ax[:set_xlim]((xmin, xmax))
    ax[:set_ylim]((xmin, xmax))
end;

figure(figsize=(3,3))
render_trace(trace);

We obtain the improved variant

function render_trace(trace; show_data=true)
    fig, ax = plt[:subplots](figsize=(3,3))
    xs = get_args(trace)[1]
    assmt = get_assmt(trace)
    if show_data
        ys = [assmt[(:y, i)] for i=1:length(xs)]
        ax[:scatter](xs, ys, c="black")
    end
    slope = assmt[:slope]
    intercept = assmt[:intercept]
    xmin = minimum(xs)
    xmax = maximum(xs)
    plot([xmin, xmax], slope *  [xmin, xmax] .+ intercept, color="black", alpha=0.5)
    ax[:set_xlim]((xmin, xmax))
    ax[:set_ylim]((xmin, xmax))
    return fig, ax
end;

fig, ax = render_trace(trace);

without any global fig or ax = gca() objects lying around.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant