Graph

Basic Graph

Geom_abline

Line

set.seed(1234)

dat<-data.frame(cond=factor(rep(c("A","B"),each=200)),rating=c(rnorm(200),rnorm(200,mean=.8)))

p<- ggplot(dat,aes(x=rating))+geom_histogram(binwidth = .5, colour="black",fill="white")+geom_vline(aes(xintercept=mean(rating,na.rm=TRUE)),color="red",linetype="dashed",size=1)+theme_minimal()

fig<-ggplotly(p)

fig

Geom_bar

Stacked Bar Chart

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

p <- ggplot(DF1, aes(x = Rank, y = value, fill = variable)) +
  geom_bar(stat = "identity")

fig <- ggplotly(p)

fig

Geom_contour

geom_contour produces a similar output to geom_density_2d, except it uses a third variable for the values rather than frequency. The volcano dataset comes pre-loaded on R

Color

library(plotly)
library(reshape2)
df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2, z= value)) +
  geom_contour() +
  scale_fill_distiller(palette = "Spectral", direction = -1)
fig <- ggplotly(p)

fig

Fill

library(plotly)
library(reshape2)
df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2, z= value)) +
  stat_contour(geom="polygon",aes(fill=stat(level))) +
  scale_fill_distiller(palette = "Spectral", direction = -1)

ggplotly(p)

Geom_density

Add a smooth density estimate calculated by stat_density with ggplot2 and R

set.seed(1234)

dfGamma = data.frame(nu75 = rgamma(100, 0.75),
           nu1 = rgamma(100, 1),
           nu2 = rgamma(100, 2))

dfGamma = stack(dfGamma)

p <- ggplot(dfGamma, aes(x = values)) +
  stat_density(aes(group = ind, color = ind),position="identity",geom="line")

fig <- ggplotly(p)

fig

Over scatterplot

library(plotly)
set.seed(123)

df <- data.frame(x <- rchisq(1000, 10, 10),
                 y <- rnorm(1000))

p <- ggplot(df, aes(x, y)) + 
  geom_point(alpha = 0.5) + 
  geom_density_2d() + 
  theme(panel.background = element_rect(fill = '#ffffff')) + 
  ggtitle("2D density plot with scatterplot overlay")

fig <- ggplotly(p)

fig

Kernel Density Estimate

p <- ggplot(diamonds, aes(x = price)) + 
  geom_density(aes(fill = "epanechnikov"), kernel = "epanechnikov") + 
  facet_grid(~cut) + 
  ggtitle("Kernel density estimate with Facets")

fig <- ggplotly(p)

fig

Geom_jitter

Basic Graph

library(plotly)
district_density <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/district_density.csv",
                             stringsAsFactors = FALSE)
district_density$cluster <- factor(district_density$cluster, levels=c("Pure urban", "Urban-suburban mix", "Dense suburban", "Sparse suburban", "Rural-suburban mix", "Pure rural"))
district_density$region <- factor(district_density$region, levels=c("West", "South", "Midwest", "Northeast"))

p <- ggplot(district_density,aes(x=cluster, y=dem_margin, colour=region)) +
  geom_jitter(aes(text=paste("district: ", cd_code)), width=0.25, alpha=0.5, ) +
  geom_hline(yintercept=0) +
  theme(axis.text.x = element_text(angle = -30, hjust = 0.1)) +
  labs(title = "Democratic performance in the 2018 House elections, by region and density",
       x = "Density Index from CityLab",
       y = "Democratic Margin of Victory/Defeat")
## Warning: Ignoring unknown aesthetics: text
fig <- ggplotly(p)

fig

Add Boxplot

library(plotly)
district_density <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/district_density.csv",
                             stringsAsFactors = FALSE)
district_density$cluster <- factor(district_density$cluster, levels=c("Pure urban", "Urban-suburban mix", "Dense suburban", "Sparse suburban", "Rural-suburban mix", "Pure rural"))
district_density$region <- factor(district_density$region, levels=c("West", "South", "Midwest", "Northeast"))

p <- ggplot(district_density,aes(x=cluster, y=dem_margin, colour=region)) +
  geom_jitter(aes(text=paste("district: ", cd_code)), width=0.25, alpha=0.5, ) +
  geom_hline(yintercept=0) +
  theme(axis.text.x = element_text(angle = -30, hjust = 0.1)) +
  labs(title = "Democratic performance in the 2018 House elections, by region and density",
       x = "Density Index from CityLab",
       y = "Democratic Margin of Victory/Defeat")
## Warning: Ignoring unknown aesthetics: text
fig <- ggplotly(p)

fig

Geom_line

test_data <-
  data.frame(
    var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
    var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
    date = seq(as.Date("2002-01-01"), by="1 month", length.out=100)
  )

test_data_long <- melt(test_data, id="date")  # convert to long format

p <- ggplot(data=test_data_long,
       aes(x=date, y=value, colour=variable)) +
    geom_line()

fig <- ggplotly(p)

fig

Geom_point

Scatter Chart

library(plotly)

set.seed(955)
# Make some noisily increasing data
dat <- data.frame(cond = rep(c("A", "B"), each=10),
                  xvar = 1:20 + rnorm(20,sd=3),
                  yvar = 1:20 + rnorm(20,sd=3))

p <- ggplot(dat, aes(x=xvar, y=yvar)) +
    geom_point(shape=1)      # Use hollow circles

fig <- ggplotly(p)

fig

Liner Regression w/ smooth

library(plotly)

set.seed(955)
# Make some noisily increasing data
dat <- data.frame(cond = rep(c("A", "B"), each=10),
                  xvar = 1:20 + rnorm(20,sd=3),
                  yvar = 1:20 + rnorm(20,sd=3))

p <- ggplot(dat, aes(x=xvar, y=yvar)) +
    geom_point(shape=1) +    # Use hollow circles
    geom_smooth(method=lm)   # Add linear regression line


fig <- ggplotly(p)
## `geom_smooth()` using formula 'y ~ x'
fig

Geom_raster

Basic 2d Heatmap

library(reshape2)
library(plotly)

df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2)) +
  geom_raster(aes(fill=value)) +
  labs(x="West to East",
       y="North to South",
       title = "Elevation map of Maunga Whau")

ggplotly(p)
## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Customized 2d Heatmap

library(reshape2)
library(plotly)

df <- melt(volcano)

p <- ggplot(df, aes(Var1, Var2)) +
  geom_raster(aes(fill=value)) +
  scale_fill_distiller(palette = "Spectral", direction = -1) +
  labs(x="West to East",
       y="North to South",
       title = "Elevation map of Maunga Whau",
       fill = "Elevation") +
  theme(text = element_text(family = 'Fira Sans'),
        plot.title = element_text(hjust = 0.5))

ggplotly(p)
## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

geom_polygon

Basic Polygon

library(plotly)

ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))

values <- data.frame(
  id = ids,
  value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5)
)

positions <- data.frame(
  id = rep(ids, each = 4),
  x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
  0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
  y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
  2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
)

datapoly <- merge(values, positions, by=c("id"))

p <- ggplot(datapoly, aes(x=x, y=y)) + geom_polygon(aes(fill=value, group=id))

fig <- ggplotly(p)

fig

Distribution

library(plotly)

x=seq(-2,2,length=200)
dat <- data.frame(
  norm = dnorm(x,mean=0,sd=0.2),
  logistic = dlogis(x,location=0,scale=0.2), x = x
)
p <- ggplot(data=dat, aes(x=x)) +
  geom_polygon(aes(y=norm), fill="red", alpha=0.6) +
  geom_polygon(aes(y=logistic), fill="blue", alpha=0.6) +
  xlab("z") + ylab("") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))

fig <- ggplotly(p)

fig

geom_tile

Basic geom_tile graph

library(plotly)
spinrates <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/spinrates.csv",
                      stringsAsFactors = FALSE)

p <- ggplot(spinrates, aes(x=velocity, y=spinrate)) +
  geom_tile(aes(fill = swing_miss)) +
  scale_fill_distiller(palette = "YlGnBu") +
  labs(title = "Likelihood of swinging and missing on a fastball",
       y = "spin rate (rpm)")

ggplotly(p)
## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Adjusting appearance

library(plotly)
spinrates <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/spinrates.csv",
                      stringsAsFactors = FALSE)

p <- ggplot(spinrates, aes(x=velocity, y=spinrate)) +
  geom_tile(aes(fill = swing_miss)) +
  scale_fill_distiller(palette = "YlGnBu", direction = 1) +
  theme_light() +
  labs(title = "Likelihood of swinging and missing on a fastball",
       y = "spin rate (rpm)")

ggplotly(p)
## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

geom_rect

geom_rect with a line graph

df <- data.frame(name = c("Nixon", "Ford", "Carter", "Reagan", "Bush", "Clinton", "Bush", "Obama"),
                   start = as.Date(c("1969-01-20", "1974-08-09", "1977-01-20", "1981-01-20",
                             "1989-01-20", "1993-01-20", "2001-01-20", "2009-01-20")),
                   end = as.Date(c("1974-08-09", "1977-01-20", "1981-01-20", "1989-01-20", 
                           "1993-01-20", "2001-01-20", "2009-01-20", "2017-01-20")),
                   party = c("R", "R", "D", "R", "R", "D", "R", "D"),
                   stringsAsFactors = FALSE) %>%
  mutate(median_x = start + floor((end-start)/2))

p <- ggplot(economics, aes(x=date,y=unemploy)) +
  geom_rect(data=df, aes(NULL,NULL,xmin=start,xmax=end,fill=party),
            ymin=0,ymax=16000, colour="white", size=0.5, alpha=0.2) +
  scale_fill_manual(values=c("R" = "red", "D" = "blue")) +
  geom_line() +
  geom_text(data=df,aes(x=median_x,y=3000,label=name), size=3) +
  labs(title = "Unemmployment numbers since 1967",
       y = "No. unemployed (x 1000)")
fig <- ggplotly(p)

fig

Geom_rug

library(plotly)

df <- MASS::birthwt

df <- with(df, {
  race <- factor(race, labels = c("white", "black", "other"))
  ptd <- factor(ptl > 0)
  ftv <- factor(ftv)
  levels(ftv)[-(1:2)] <- "2+"
  data.frame(low = factor(low), age, lwt, race, smoke = (smoke > 0),
             ptd, ht = (ht > 0), ui = (ui > 0), ftv, bwt)
})

p <- ggplot(df, aes(lwt, bwt, colour = smoke)) +
  geom_point(size = 1) +
  geom_rug()

fig <- ggplotly(p)

fig

Statistics Graph

Geom_bind2d

Basic 2d Heatmap

library(plotly)

english_french <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/english_french.csv",stringsAsFactors = FALSE)

p<- ggplot(english_french,aes(x=engperc,y=frenperc))+geom_bin2d()+labs(title= "Distribution of Canadian areas by English and French fluency", x="% fluent in English",y="% fluent in French",fill="# of census \ nsubdivisions")+scale_fill_gradient(low="lightblue1",high="darkblue",na.value = "black")

fig<- ggplotly(p)

fig
## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

With Facets

p <- ggplot(english_french, aes(x=engperc,y=frenperc, weight=total)) + 
  geom_bin2d(bins = 20) +
  facet_wrap(~factor(region, levels = c("Atlantic","Québec","Ontario","Prairies","British Columbia"))) +
  scale_fill_gradient(low="lightblue1",high="darkblue",trans="log10") +
  labs(title = "Distribution of Canadian towns by English and French fluency",
       x = "% fluent in English",
       y = "% fluent in French",
       fill = "population")
fig <- ggplotly(p)


fig
## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

## Warning: 'heatmap' objects don't have these attributes: 'showlegend'
## Valid attributes include:
## 'type', 'visible', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'z', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'hovertext', 'transpose', 'xtype', 'ytype', 'zsmooth', 'connectgaps', 'xgap', 'ygap', 'zhoverformat', 'hovertemplate', 'zauto', 'zmin', 'zmax', 'zmid', 'colorscale', 'autocolorscale', 'reversescale', 'showscale', 'colorbar', 'coloraxis', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'zsrc', 'xsrc', 'ysrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Geom_count

Basic geom_count Plot

  • geom_count is a way to plot 2 variables that are not continous. Here’s a modified version of the nycflights13 dataset
library(plotly)
flightdata <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/flightdata.csv", stringsAsFactors = FALSE)

p <- ggplot(flightdata, aes(y=airline, x=dest, colour = dest, group=airport)) +
  geom_count(alpha=0.5) +
  labs(title = "Flights from New York to major domestic destinations",
       x = "Origin and destination",
       y = "Airline",
       size = "")

ggplotly(p)

Geom_boxplot

Basic Boxplot

set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))

p <- ggplot(dat, aes(x=cond, y=rating)) + geom_boxplot()

fig <- ggplotly(p)

Colored Boxplot

library(plotly)

set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))

p <- ggplot(dat, aes(x=cond, y=rating, fill=cond)) + geom_boxplot() +
    guides(fill=FALSE) + coord_flip()

fig <- ggplotly(p)

fig

Geom_hex

Basic 2d Heatmap

library(plotly)

english_french <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/english_french.csv",stringsAsFactors = FALSE)

p <- ggplot(english_french, aes(x=engperc,y=frenperc)) + 
  geom_hex() +
  labs(title = "Distribution of Canadian areas by English and French fluency",
       x = "% fluent in English",
       y = "% fluent in French",
       fill = "# of census \nsubdivisions")
fig <- ggplotly(p)

fig

Customized Colours

library(plotly)

english_french <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/english_french.csv",stringsAsFactors = FALSE)

p <- ggplot(english_french, aes(x=engperc,y=frenperc)) + 
  geom_hex() +
  scale_fill_gradient(low="lightblue1",high="darkblue",trans="log10") +
  labs(title = "Distribution of Canadian towns by English and French fluency",
       x = "% fluent in English",
       y = "% fluent in French",
       fill = "# of census \nsubdivisions")
fig <- ggplotly(p)

fig

Weighted Data

library(plotly)

english_french <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/english_french.csv",stringsAsFactors = FALSE)

p <- ggplot(english_french, aes(x=engperc, y=frenperc, weight=total)) + 
  geom_hex() +
  scale_fill_gradient(low="lightblue1",high="darkblue",trans="log10") +
  labs(title = "Distribution of the Canadian population by English and French fluency",
       x = "% fluent in English",
       y = "% fluent in French",
       fill = "population")
fig <- ggplotly(p)

fig

Geom_histogram

Basic Histogram

library(plotly)

dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))

p <- ggplot(dat,aes(x=xx)) +
    geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)

fig <- ggplotly(p)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
fig

Add Lines

library(plotly)

df1 <- data.frame(cond = factor( rep(c("A","B"), each=200) ),
                  rating = c(rnorm(200),rnorm(200, mean=.8)))

df2 <- data.frame(x=c(.5,1),cond=factor(c("A","B")))

p <- ggplot(data=df1, aes(x=rating, fill=cond)) +
    geom_vline(xintercept=c(.5,1)) +
    geom_histogram(binwidth=.5, position="dodge")

fig <- ggplotly(p)

fig

#### Probability & Density

library(plotly)

df <- data.frame(x = rnorm(1000))

p <- ggplot(df, aes(x=x)) +
    geom_histogram(aes(y = ..density..), binwidth=density(df$x)$bw) +
    geom_density(fill="red", alpha = 0.2)

fig <- ggplotly(p)

fig

Geom_quantile

Basic Example

While common linear regrssion is a method of estimating the conditional mean of variable y based on the values of variables x, quantile regression is a method that can give the conditional median (50th percentile) as well as any other quantile

This dataset gives the effect of the mother’s weight on her baby’s birth weight, further divided according to whether the smokers or not

df <- MASS::birthwt

df <- with(df, { #Make sure variables properly show up as categories
  race <- factor(race, labels = c("white", "black", "other"))
  ptd <- factor(ptl > 0)
  ftv <- factor(ftv)
  levels(ftv)[-(1:2)] <- "2+"
  data.frame(low = factor(low), age, lwt, race, smoke = (smoke > 0),
             ptd, ht = (ht > 0), ui = (ui > 0), ftv, bwt)
})

p <- ggplot(df, aes(lwt, bwt, colour = smoke)) +
  geom_point(size = 1) +
  geom_quantile(quantiles = 0.5)

fig <- ggplotly(p)
## Smoothing formula not specified. Using: y ~ x
## Smoothing formula not specified. Using: y ~ x
fig

With Quantiles

library(plotly)
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
## The following object is masked from 'package:plotly':
## 
##     select
library(dplyr)

df <- MASS::birthwt

df <- with(df, {
  race <- factor(race, labels = c("white", "black", "other"))
  ptd <- factor(ptl > 0)
  ftv <- factor(ftv)
  levels(ftv)[-(1:2)] <- "2+"
  data.frame(low = factor(low), age, lwt, race, smoke = (smoke > 0),
             ptd, ht = (ht > 0), ui = (ui > 0), ftv, bwt)
})

p <- ggplot(df, aes(lwt, bwt, colour=smoke)) +
  geom_point(size = 1) +
  geom_quantile(quantiles = c(0.1, 0.5, 0.9), size = 2, aes(alpha = ..quantile..)) +
  scale_alpha(range = c(0.3, 0.7))
fig <- ggplotly(p)
## Smoothing formula not specified. Using: y ~ x
## Smoothing formula not specified. Using: y ~ x
fig

Geom_ribbon

library(plotly)

set.seed(1)
y <- sin(seq(1, 2*pi, length.out = 100))
x <- 1:100
plotdata <- data.frame(x=x, y=y, lower = (y+runif(100, -1, -0.5)), upper = (y+runif(100, 0.5, 1)))

p <- ggplot(plotdata) + geom_line(aes(y=y, x=x, colour = "sin"))+
    geom_ribbon(aes(ymin=lower, ymax=upper, x=x, fill = "band"), alpha = 0.3)+
    scale_colour_manual("",values="blue")+
    scale_fill_manual("",values="grey12")

fig <- ggplotly()

fig

Geom_smooth

library(plotly)

the.data <- read.table( header=TRUE, sep=",",
                        text="source,year,value
    S1,1976,56.98
    S1,1977,55.26
    S1,1978,68.83
    S1,1979,59.70
    S1,1980,57.58
    S1,1981,61.54
    S1,1982,48.65
    S1,1983,53.45
    S1,1984,45.95
    S1,1985,51.95
    S1,1986,51.85
    S1,1987,54.55
    S1,1988,51.61
    S1,1989,52.24
    S1,1990,49.28
    S1,1991,57.33
    S1,1992,51.28
    S1,1993,55.07
    S1,1994,50.88
    S2,1993,54.90
    S2,1994,51.20
    S2,1995,52.10
    S2,1996,51.40
    S3,2002,57.95
    S3,2003,47.95
    S3,2004,48.15
    S3,2005,37.80
    S3,2006,56.96
    S3,2007,48.91
    S3,2008,44.00
    S3,2009,45.35
    S3,2010,49.40
    S3,2011,51.19")

cutoff <- data.frame( x = c(-Inf, Inf), y = 50, cutoff = factor(50) )

p <- ggplot(the.data, aes( year, value ) ) +
    geom_point(aes( colour = source )) +
    geom_smooth(aes( group = 1 )) +
    geom_hline(yintercept = 50)

fig <- ggplotly(p)
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
fig

Geom_density2d

Basic 2D Graph

library(plotly)
beers <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/beers.csv", stringsAsFactors = FALSE)

p <- ggplot(beers, aes(x=abv, y=ibu)) +
  geom_density2d() +
  labs(y = "bitterness (IBU)",
       x = "alcohol volume (ABV)",
       title = "Craft beers from American breweries")

ggplotly(p)
## Warning: Removed 1005 rows containing non-finite values (stat_density2d).

Preset Colourscale

library(plotly)
beers <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/beers.csv", stringsAsFactors = FALSE)

p <- ggplot(beers, aes(x=abv, y=ibu)) +
  stat_density2d(aes(fill = stat(level)), geom="polygon") +
  scale_fill_viridis_c(option = "plasma") +
  theme(legend.position = "magma") +
  labs(y = "bitterness (IBU)",
       x = "alcohol volume (ABV)",
       title = "Craft beers from American breweries")

ggplotly(p)
## Warning: Removed 1005 rows containing non-finite values (stat_density2d).

Geom_violin

Flipping the Axes

library(plotly)
district_density <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/district_density.csv", stringsAsFactors = FALSE)
district_density$cluster <- factor(district_density$cluster, levels=c("Pure urban", "Urban-suburban mix", "Dense suburban", "Sparse suburban", "Rural-suburban mix", "Pure rural"))
district_density$region <- factor(district_density$region, levels=c("West", "South", "Midwest", "Northeast"))

p <- ggplot(district_density,aes(x=cluster, y=dem_margin, fill=cluster)) +
  geom_violin(colour=NA) +
  geom_hline(yintercept=0, alpha=0.5) +
  labs(title = "Democratic performance in the 2018 House elections, by region and density",
       x = "Density Index\nfrom CityLab",
       y = "Margin of Victory/Defeat") +
  coord_flip()

ggplotly(p)

Animations

Multiple Trace Animations

library(plotly)
library(gapminder)


p <- ggplot(gapminder, aes(gdpPercap, lifeExp, color = continent)) +
  geom_point(aes(size = pop, frame = year, ids = country)) +
  scale_x_log10()
## Warning: Ignoring unknown aesthetics: frame, ids
fig <- ggplotly(p)

fig

Add Animation Options

library(plotly)

fig <- fig %>% 
  animation_opts(
    1000, easing = "elastic", redraw = FALSE
  )

fig