Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ggplot and ggplotly

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

like image 685
GKerv Avatar asked May 29 '18 15:05

GKerv


People also ask

Is there a Ggplot for Python?

Using ggplot in Python allows you to build visualizations incrementally, first focusing on your data and then adding and tuning components to improve its graphical representation.

What is the difference between Ggplot and plotly?

Aesthetically, many users consider ggplot2 to be better looking than Plotly, due to its margins and points. In terms of speed, ggplot2 tends to run much slower than Plotly. With regard to integration, both Plotly and ggplot2 can integrate with a variety of tools, like Python, MATLAB, Jupyter, and React.

What package is Ggplotly?

Plotly is an R package for creating interactive web-based graphs via plotly's JavaScript graphing library, plotly.

How do I change to plotly in ggplot2?

First of all, create a data frame. Then, create a ggplot2 graph and save it in an object. After that, load plotly package and create the ggplot2 graph using ggplotly function.


2 Answers

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())
like image 197
mralbu Avatar answered Sep 28 '22 12:09

mralbu


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.

like image 29
Laughingrice Avatar answered Sep 28 '22 14:09

Laughingrice