The plotly
package allows to build interactive charts directly from R
. Here is a application to area chart, using both the plot_ly()
and ggplotly()
functions.
ggplotly()
functionThis post follows the previous basic area chart built with ggplot2.
The idea is to turn the chart interactive:
This is done thanks to the ggplotly()
function of the plotly
package that turn any ggplot2
chart object interactive.
# Libraries
library(ggplot2)
library(dplyr)
library(plotly)
library(hrbrthemes)
# Load dataset from github
data <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered.csv", header=T)
data$date <- as.Date(data$date)
# Usual area chart
p <- data %>%
ggplot( aes(x=date, y=value)) +
geom_area(fill="#69b3a2", alpha=0.5) +
geom_line(color="#69b3a2") +
ylab("bitcoin price ($)") +
theme_ipsum()
# Turn it interactive with ggplotly
p <- ggplotly(p)
p
# save the widget
# library(htmlwidgets)
# saveWidget(p, file=paste0( getwd(), "/HtmlWidget/ggplotlyAreachart.html"))
plot_ly()
The ggplotly()
function above takes as input a ggplot2 chart and turn it interactive.
But the plotly
package also allows to build interactive charts using its own function: plot_ly()
.
Pro: it will allows a greater control of chart style. See the whole API for customization.
Con: you have to learn a new API, although you probably already know ggplot2
# library
library(plotly)
# Create data
var1 <- seq(1,8)
var2 <- c(0,1,4,1,8,7,5,4)
var3 <- c(7,8,4,2,1,2,0,1)
# Area chart with 2 groups
p <- plot_ly(x = var1, y = var2, type="scatter", mode="markers", fill = "tozeroy")
p <- add_trace(p, x = var1, y = var3, type="scatter", mode="markers", fill = "tonexty")
p
# save the widget
# library(htmlwidgets)
# saveWidget(p, file=paste0( getwd(), "/HtmlWidget/plotlyAreachart.html"))