Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Plumbr to other options for making a chart with R in a Python script

Tags:

python

r

ggplot2

I plan on making a chart with ggplot in a python script. These are details about the project:

  • I have a script that runs on a remote machine and I can install anything within reason on the machine

  • The script runs in python and has data that I want to visualize stored as a dictionary

  • The script runs daily and the data always has the same structure

I think my best bet is to do this...

  • Write an R script that takes the data and creates the ggplot visualization

  • Use plumbr to create a rest API for my script

  • Send a call to the rest API and get a PNG of my plot in return

I'm also familiar with ggpy by yhat and I'm even wondering if I can install R on the machine and just send code directly to the machine to process it without having RStudio.

Would plumbr be a recommended and secure implementation?

This is a reproducible example-

my_data = [{"Chicago": "30"} {"New York": "50"}], [{"Cincinatti": "70"}, {"Green Bay": "95"}] 

**{this is the part that's missing}**

library(ggplot)
my_data %>% ggplot(aes(city_name, value)) + geom_col()

png("my_bar_chart.png", my_data)
like image 937
Cauder Avatar asked May 03 '20 02:05

Cauder


1 Answers

As mentioned in the comments, most of your question should be answered here: Using R in Python with Rpy2: how to ggplot2?.

You can load ggplot with:

import rpy2.robjects.packages as packages
import rpy2.robjects.lib.ggplot2 as ggp2

assuming of course you have ggplot2 + dependencies available.

Then you can almost use R syntax, except that you put ggp2. in front of every command.

E.g: the Python equivilant of ggplot(mtcars) would be ggp2.ggplot(mtcars).

Your example: (not tested)

my_data = [{"Chicago": "30"} {"New York": "50"}], [{"Cincinatti": "70"}, {"Green Bay": "95"}] 

import rpy2.robjects.packages as packages
import rpy2.robjects.lib.ggp2 as ggp2

plot = ggp2.ggplot(my_data) + 
  ggp2.aes(city_name, value)) + 
  ggp2.geom_col()

plot.plot()

R("dev.copy(png, 'my_data.png')")
like image 163
Tonio Liebrand Avatar answered Sep 28 '22 11:09

Tonio Liebrand