Coolio2654
Coolio2654

Reputation: 1739

How to graph a function in Python using plotnine library

I've been a longtime R user, recently transitioning over to Python, and I've been trying to carry over my knowledge of plotting with ggplot2, since it is so intuitive. Plotnine is supposedly the most ggplot2-esque plotting library, and I've successfully recreated most graphs with it, except critically how to plot regular functions.

In base R, you can easily define an eq., as in so, input the result into a stat_function() layer, and set the limits of the graph in place of the data arg., and successfully plot a parabola or the like. However, the syntax for setting the graph's limits must be different in Python (perhaps using numpy?), and equations are defined using sympy, which is another divergence for me.

So how would I go about plotting functions with plotnine? The above two hurdles are the two differences with ggplot2 that I think are causing me trouble, since plotnine has so few examples online.

P.S. This is an example of what I want to recreate in Python using plotnine:

> library(ggplot2)
> basic_plot <- function(x) x^2 + 2.5
> graph <- ggplot(data.frame(x=c(-5,5)), aes(x=x)) +
+ stat_function(fun = basic_plot)
> graph

Upvotes: 4

Views: 2116

Answers (2)

bill fite
bill fite

Reputation: 43

One of the main differences that caused me problems was the same as posted in the question. Specifically:

in R aes(x = x) or aes(x)

in plotnine aes(x = 'x')

Upvotes: 1

erocoar
erocoar

Reputation: 5893

You do not need numpy, it works just fine the "standard" way! :)

from plotnine import *
import pandas as pd

(ggplot(pd.DataFrame(data={"x": [-5, 5]}), aes(x="x"))
    + stat_function(fun=lambda x: x**2+2.5))

enter image description here

Upvotes: 5

Related Questions