Is it possible to use rpy2 (calling ggplot2) with IPython notebooks, and then save them (and share on NBViewer like other notebooks http://nbviewer.ipython.org/)? Is there any challenge in having the rpy2 ggplots appear in the notebook and/or interactively? It would be helpful if someone could provide an example session and its output of making a ggplot2 figure within a notebook using rpy2 in IPython.
This was written without looking the code in rmagic.
They have have a more clever way to do it (I have 11 lines of code).
import uuid
from rpy2.robjects.packages import importr
from IPython.core.display import Image
grdevices = importr('grDevices')
def ggplot_notebook(gg, width = 800, height = 600):
fn = '{uuid}.png'.format(uuid = uuid.uuid4())
grdevices.png(fn, width = width, height = height)
gg.plot()
grdevices.dev_off()
return Image(filename=fn)
To try it:
from rpy2.robjects.lib import ggplot2
from rpy2.robjects import Formula
datasets = importr('datasets')
mtcars = datasets.__rdata__.fetch('mtcars')['mtcars']
p = ggplot2.ggplot(mtcars) + \
ggplot2.aes_string(x='mpg', y='cyl') + \
ggplot2.geom_point() + \
ggplot2.geom_smooth() + \
ggplot2.facet_wrap(Formula('~ am'))
ggplot_notebook(p, height=300)
It's possible with the rmagic extension, which uses rpy2. You seem to need to print() the figure to show it, though. Here's an example session: http://nbviewer.ipython.org/5029692
If you prefer to use rpy2 directly, it must be possible. Have a look at the rpy2 documentation for ggplot2. To get it into the notebook, you can draw to a PNG/SVG device, then read it from the Python side (this is what rmagic does).
Related
I installed dtreebiz and wanted to make a three plot. I did exactly what example codes say as below, but keep getting "NameError: name 'dtreeviz' is not defined".
from dtreeviz.trees import *
viz = dtreeviz(lgbm,
x_data = df_X_train,
y_data = df_y_train,
target_name = TARGET,
feature_names = df_X_train.columns.tolist(),
tree_index = 0)
viz
I checked the version using pip show dtreeviz and confirmed version 2.1.3 is installed. I am using Spyder mostly but I also tried the same thing with Jupyter Notebook and got the same error.
You need to add
import dtreeviz
to your code (see the Quick Start in dtreeviz github page). Importing all the symbols from dtreeviz.trees, like you're doing with
from dtreeviz.trees import *
imports the symbols in the trees module only.
There was some compatibility issues from version 1 to 2.
I would suggest to start using the new 2.0 API :)
For the old API, you could try:
from dtreeviz import *
viz = dtreeviz(lgbm,
x_data = df_X_train,
y_data = df_y_train,
target_name = TARGET,
feature_names = df_X_train.columns.tolist(),
tree_index = 0)
I am using Jupyter in a Conda environment:
import igl
import meshplot as mp
import numpy as np
v, f = igl.read_triangle_mesh("./earth.ply")
k = igl.gaussian_curvature(v, f)
mp.plot(v, f, k, return_plot = True)
OUTPUT:
<meshplot.Viewer.Viewer at 0x1b53eb03fa0>
it is not displaying the mesh. it just outputs the location it stored in memory. Please help me.
It seems that you have your meshplot.rendertype set to "OFFLINE".
If you are using this code in a jupyter notebook and want to display the mesh, then just switch rendertype to "JUPYTER", by executing mp.jupyter() somewhere before your plot() command.
If you are running the code as a normal python program, you can export this View object as a HTML frame using the View.to_html() method. Then you can insert this frame into a html file and view it in a browser.
You can check out the source code for switching rendertype here, how the mp.plot function works here. The View class with the to_html method is defined here.
Former R user, I used to combine extensively ggplot and plot_ly libraries via the ggplotly() function to display data.
Newly arrived in Python, I see that the ggplot library is available, but cant find anything on a simple combination with plotly for graphical reactive displays.
What I would look for is something like :
from ggplot import*
import numpy as np
import pandas as pd
a = pd.DataFrame({'grid': np.arange(-4, 4),
'test_data': np.random.random_integers(0, 10,8)})
p2 = ggplot(a, aes(x = 'grid', y = 'test_data'))+geom_line()
p2
ggplotly(p2)
Where the last line would launch a classic plotly dynamic viewer with all the great functionalities of mouse graphical interactions, curves selections and so on...
Thanks for your help :),
Guillaume
This open plotnine issue describes a similar enhancement request.
Currently the mpl_to_plotly function seems to work sometimes (for some geoms?), but not consistently. The following code, seems to work ok.
from plotnine import *
from plotly.tools import mpl_to_plotly as ggplotly
import numpy as np
import pandas as pd
a = pd.DataFrame({'grid': np.arange(-4, 4),
'test_data': np.random.randint(0, 10,8)})
p2 = ggplot(a, aes(x = 'grid', y = 'test_data')) + geom_point()
ggplotly(p2.draw())
You don't need ggplotly in python if all you are seeking is an interactive interface.
ggplot (or at least plotnine, which is the implementation that I am using) uses matplotlib which is already interactive, unlike the R ggplot2 package that requires plotly on top.
I have the next code in python
import np_plots as npp
import matplotlib.pyplot as plt
import numpy as np
import math as m
import scipy
from scipy.integrate import odeint
def plotLimitCycle(bval):
rhs = lambda X, t: [-X[0]+X[1]*X[0]**2, bval - X[1]*X[0]**2]
xeq, yeq = bval, 1.0/bval
cyclerad = m.sqrt(1-bval)
nbh = min(cyclerad, 0.05)
IC = [xeq-nbh/5.0, yeq-nbh/5.0]
time_span = np.linspace(0,400,40000)
fig = plt.figure()
solution = odeint(rhs, IC, time_span)
X, Y = zip(*solution)
plt.plot(X, Y)
axes = plt.gca()
axXmin, axXmax = axes.get_xlim()
axYmin, axYmax = axes.get_ylim()
xmin = max(-15, axXmin)
xmax = min(15, axXmax)
ymin = max(-15, axYmin)
ymax = min(15, axYmax)
X,Y,U,V = npp.ezDomainQuiver2D([[xmin, xmax],[ymin, ymax]],[25,25],lambda X: rhs(X, 0),Normalize=True)
plt.quiver(X,Y,U,V)
plt.scatter([xeq],[yeq], color='red')
plt.xlim([xmin, xmax])
plt.ylim([ymin, ymax])
plt.axes().set_aspect('equal', 'datalim')
plt.show()
It work pretty well on my friend computer because he showed me the plots but I can't make it run in mine, I'm using Python 3.5.0cr1 Shell to run it out but it always came with te next error:
**Traceback (most recent call last):
File "C:\Users\PankePünke\Desktop\limites.py", line 1, in <module>
import np_plots as npp
ImportError: No module named 'np_plots'**
I'm totally new in Python programming and my friend made this program for me in order to make some advances in my thesis but I want to continue working with this program and get the plots from this. I do not know how to install or what kind of procceddure I should follow in order to get what I want (the plots and graphics that this program make) So... I'll be very thankful if somebody can help me in not a advance way, because how a wrote I'm totally new in Python, I just installed it and that is all.
You friend had a lib called np_plots on their computer, it is not part of the standard lib so you need to also install/get it on your comp or the code will not run. Most likely your friend actually wrote the code as I cannot see any mention of that lib anywhere so you will have to get it from them.
Apart from your friends lib, scipy and numpy are also not in the standard library, they do come with some distributions like Canopy but if you just installed a regular version of python you will need to install those also.
Might be worth checking out pip as it is the de-facto standard package manager for python.
In Spyder 2 (Anaconda distribution) and in the IPython QT Console I'm able to print results of symbolic calculations (from an answer I got for a previous post) but I can't get equations in strings to print with the a IPython's Rich Display System:
from sympy import *
from IPython.display import display, Math
init_printing(use_unicode=False, wrap_line=False, no_global=True)
x, y, z = symbols('x y z')
#----- prints correctly
ii = integrate(x**2 + x + 1, x)
display(ii)
#----- does not print
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
The above prints the results of the integrate correctly but the Math() does not print (no error -- just skips it). Note it all works in SciPy web notebook.
Thank you!
The Math class doesn't generate the rendered image from your Latex, that's why it doesn't work directly.
To get what you want you need to use this code
from IPython.display import Image, display
from IPython.lib.latextools import latex_to_png
eq = r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'
data = latex_to_png(eq, wrap=True)
display(Image(data=data))
Then you will see the right image
Hello guys im still having the problem, whe i use
from IPython.display import display, Math, Latex
display((Math(r'P(Purchase|Male)= \frac{Numero\ total\ de\ compras\ hechas\ por\ hombres\}{Total\ de\ hombres\ en\ el\ grupo\} = \frac{Purchase\cap Male}{Male}')))
on jupyter it works fine, but when i do the exact same code on spyder it doesnt work
im using python 3.6 , spyder 3.3.3
also i tried the marked asnwer but latex_to_png makes a NoneType Object on spyder