plotly is one of the most popular open source java scrip libraries for creating interactive web-based graphs. We can zoom into the map as well as we can find the values by simply moving the cursors on to each point on the graph. plotly R package contain ggplotly to convert ggplot2 graphs into plotly.
We can create a basic plotly graph by simply using ‘plotly’ function. It can produce various statistical graphs by using ‘type’ argument. Here is the simple basic usage with basic R plot.
library(ggplot2)
library(plotly)
plot_ly(mtcars,x = ~wt,y = ~mpg,color=~cyl,type="scatter",mode="markers",colors=c("red", "blue", "green"),
marker = list(size = 10))
The text parameter into plotly can be used to nice format the popup values.
Diamonds<-diamonds[sample(nrow(diamonds),1000),]
plot_ly(Diamonds,x=~carat,y=~price,color = ~carat, size = ~carat,
type="scatter",mode="markers",text = ~paste("Price: ", price, '$<br>Cut:', cut, '$<br>Carat:',carat))
In order to display graphs generated thru ggplot2, we simply need to pass the ggplot2 graph to ggplotly package. Here is the sample e.g. Notice that, we don’t need to create ‘text’ argument to show the popup values.
g<-ggplot(Diamonds,aes(carat,price,color=clarity))+facet_wrap(~cut)
g<-g+geom_point()+ggtitle("Diamonds data")
ggplotly(g)
Note that the warning = FALSE parameter was added to the code chunk to prevent the R code display its output while generating the plot.