My first try at plotly

I have been hearing a lot about this new tool for interactive plotting, called plotly, and I have been wanting to try it out for a while. So this is my first attempt at using plotly with R and RStudio.

The packages that are needed are just devtools (for installing the plotly library using install_github), and ggplot2 makes great plots that are compatible with plotly.

This first bit of code is just for loading packages and installing plotly. (note: I am also loading RCurl here to facilitate grabbing data from GitHub)


 ## Loading required package: devtools


 ## Loading required package: ggplot2


 ## Loading required package: RCurl
 ## Loading required package: bitops

 if (!require(plotly)) {
 install_github("plotly", "ropensci")
 ## Loading required package: plotly
 ## Loading required package: RJSONIO



Now that I have installed the plotly package, I need to create a plotly object in order to sign into my Plotly API account. This was made very easy, I basically just copied the code from their online GUI.

py <- plotly(username = "jjborrelli", key = "mykey")


I also signed up for a plotly API using their online GUI. Once I signed up my username and key were given to me through the GUI.

Now I can start plotting:

First I load in some data to make the plot. This particular data is the trophic position and omnivory index for the species in 50 different food webs that I have been collecting.

url <- getURL("")
tinfo <- read.csv(text = url, row.names = 1)

Then create a plot with ggplot2, here I am plotting the omnivory index (OI) as a function of trophic position (TL).

g <- ggplot(tinfo, aes(x = TL, y = OI)) + geom_point(aes(col = L1))

The syntax to make the interactive plot is quite simply py$ggplotly()

r <- py$ggplotly(g)

This will generate a url that you can follow to view the plot.

And you can view the plot on here

So it turns out this was incredibly easy, and makes for amazing interactive graphs. I will definitely be using this tool frequently in the future.

I would love to be able to insert the interactive version of the graph here in the post, but WordPress will not let me, so in the future I may be migrating this blog from WP to a more code friendly hosting platform such as GitHub pages (powered by Jekyll).

This entry was posted in Coding and tagged , , . Bookmark the permalink.

2 Responses to My first try at plotly

  1. Cool graph! 🙂
    Note that for such quick/exploratory/research-style plotting, you can skip assignments:
    ggplot(tinfo, aes(x=TL, y=OI)) + geom_point(aes(col=L1))

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s