Skip to content

add utility method to plot the pdf of a variable #5032

@drbenvincent

Description

@drbenvincent

In discussions in PyMC Labs, a client asked if there was a simple utility function to plot the pdf of a PyMC variable.

As a quick hack I came up with the following:

Continuous

def plot_cont(self):
    """Plot pdf of continuous dist, with semi clever setting of range"""
    samples = self.random(size=10_000)
    x = np.linspace(np.min(samples), np.max(samples), 1000)
    plt.plot(x, np.exp(self.logp(x)).eval())

# add plot method to abstract class Continuous
pm.Continuous.plot = plot_cont

# example use
pm.Normal.dist(mu=1, sd=2).plot()
pm.Laplace.dist(mu=0, b=1).plot()

which results in the following
Screenshot 2021-09-28 at 17 52 24

Discrete

def plot_disc(self):
    """Plot pdf of discrete dist, with semi clever setting of range"""
    samples = self.random(size=10_000)
    x = np.arange(np.min(samples), np.max(samples)+1)
    plt.plot(x, np.exp(self.logp(x)).eval(), "-o")

# add plot method to abstract class Continuous
pm.Discrete.plot = plot_disc

# example use
pm.Binomial.dist(n=10, p=0.2).plot()
pm.Geometric.dist(p=0.5).plot()

which results in this
Screenshot 2021-09-28 at 17 53 30

So this issue is to see what people think about adding this functionality.

I've contributed example notebooks, but not to core PyMC code before, so it may be naive but... Maybe some more polished version could be added as methods of pm.Continuous and pm.Discrete?

Thoughts and feedback welcome.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions