(See the source code and more examples here: https://github.com/plotly/knitr-demos)
In ggplot2
, you plot bar charts using geom_bar
plus stat_identity
.
library(ggplot2)
library(plotly)
library(devtools)
##
## Attaching package: 'devtools'
##
## The following objects are masked from 'package:utils':
##
## ?, help
##
## The following object is masked from 'package:base':
##
## system.file
install_github("ropensci/plotly")
## Installing github repo plotly/master from ropensci
## Downloading master.zip from https://github.com/ropensci/plotly/archive/master.zip
## Installing package from /tmp/RtmpXBik3s/master.zip
## arguments 'minimized' and 'invisible' are for Windows only
## Installing plotly
## '/usr/lib/R/bin/R' --vanilla CMD INSTALL \
## '/tmp/RtmpXBik3s/devtools3f1e6fbcc5b8/plotly-master' \
## --library='/home/marianne/R/x86_64-pc-linux-gnu-library/3.1' \
## --install-tests
##
## Reloading installed plotly
# Initialize a plotly object to sign in to your Plotly API account
py <- plotly("R-demos", "p9g4f35ytd")
# Consider the following data frame
researchers <- data.frame(country=c("Canada", "Canada", "Germany", "USA"),
name=c("Warren", "Andreanne", "Stefan", "Toby"),
papers=c(23, 14, 37, 20),
field=c("Math", "Bio", "Bio", "Math"))
# Let us plot the number of papers (y) per name (x)
gg.basic <- ggplot(researchers, aes(x=name, y=papers)) +
geom_bar(stat="identity")
In R your plot looks like this:
print(gg.basic)
Now send it to Plotly!
py$ggplotly(gg.basic)
# Let us plot the number of papers (y) per country (x) splitting by field
gg.dodge <- ggplot(researchers, aes(x = country, y = papers, fill = field)) +
geom_bar(stat = "identity", position = "dodge")
In R your plot looks like this:
print(gg.dodge)
Send it to Plotly!
py$ggplotly(gg.dodge)
Oh, the default colors are different. Let us change the colors the way we like using Plotly's UI. Say we are happy with the following:
py$embed("https://plot.ly/~R-demos/11/papers-vs-country/")
# Let us plot the same thing but with a different layout (barmode='stack')
gg.stack <- ggplot(researchers, aes(x = country, y = papers, fill = field)) +
geom_bar(stat = "identity", position = "stack")
In R your plot looks like this:
print(gg.stack)
Send it to Plotly!
py$ggplotly(gg.stack)
# Let us plot the same thing but with a different layout (barmode='overlay')
gg.identity <- ggplot(researchers, aes(x = country, y = papers, fill = field)) +
geom_bar(stat = "identity", position = "identity")
In R your plot looks like this:
print(gg.identity)
Send it to Plotly!
py$ggplotly(gg.identity)
You need to hover over the 'Canada' bar to see the info for 'Bio' (i.e., 14), which lies underneath.