-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplotly_examples.Rmd
637 lines (525 loc) · 14 KB
/
plotly_examples.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
---
output:
html_document:
fig_caption: yes
fig_height: 2.5
fig_width: 4
highlight: zenburn
toc: yes
---
```{r setup, include=FALSE, cache=FALSE}
library(knitr)
# set global chunk options
opts_chunk$set(fig.path='figure/minimal-', fig.align='center', fig.show='hold', fig.height=2.5, fig.width=4, figerror=TRUE, plotly=TRUE, error=TRUE)
```
# Plotly
[Plotly](http://www.plot.ly) is a cool, open-source project ( [github](https://github.com/plotly) ) to help people get interactive plots online easily through a number of various programming languages. It's essentially brand new and I'm going to document how well it works with the popular ggplot2 package in R. This post will be updated as support for more geoms is added.
# Plotly and geoms
I'm going to test out different ggplot geoms to check for compatibility. Most examples will be taken straight from [ggplot's docs website](http://docs.ggplot2.org/current/). The master list of geoms is at the botttom of this post. Some of the plots have minor errors.
## Installing Plot.ly
installing Plot.ly is easy.
```{r, plotly=TRUE, eval=FALSE}
#autoloads ggplot
library(devtools)
install_github("plotly", "ropensci")
signup("yourusername", "[email protected]")
```
```{r, echo=FALSE}
plotly.key = 'h4lbm5pbfx'
```
```{r}
library(plotly)
py <- plotly(username= 'xysmas', key=plotly.key)
```
# the plots
## geom_abline, hline, vline
```{r lines}
coefs <- coef(lm(Sepal.Length ~ Petal.Width, data = iris))
p.iris <- ggplot(iris, aes(Petal.Width, Sepal.Length, color = Species))
p.iris <- p.iris + geom_point()
p.iris.hline <- p.iris + geom_hline(yintercept=7)
p.iris.abline <- p.iris + geom_abline(intercept=coefs[1], slope=coefs[2], colour="red", size=2)
p.iris.vline <- p.iris + geom_vline(xintercept=2)
p.iris.abline
p.iris.hline
p.iris.vline
```
```{r figerror=TRUE}
py$ggplotly(p.iris.abline)
# odd little error
py$ggplotly(p.iris.hline)
# odd little error
py$ggplotly(p.iris.vline)
```
geom_abline doesn't work.
## geom_area
```{r}
# Generate data
huron <- data.frame(year = 1875:1972, level = as.vector(LakeHuron))
library(plyr) # to access round_any
huron$decade <- round_any(huron$year, 10, floor)
h <- ggplot(huron, aes(x=year))
h <- h + geom_area(aes(y = level))
h
```
```{r}
py$ggplotly(h)
```
geom_area = FALSE!
## geom_bar
```{r bar}
bar <- ggplot(iris, aes(Species, colour=Species, fill=Species))
bar <- bar + geom_bar()
bar
```
```{r barpy}
py$ggplotly(bar)
```
Nope.
## geom_bin2d
```{r bin}
d <- ggplot(diamonds, aes(x = x, y = y)) + xlim(4,10) + ylim(4,10)
d <- d + geom_bin2d()
py$ggplotly(d)
```
Nope.
## geom_boxplot
```{r boxplot}
p.iris <- ggplot(iris, aes(Species, Sepal.Length, fill=Species))
p.iris <- p.iris + geom_boxplot()
py$ggplotly(p.iris)
```
Nope.
## geom_contour
```{r}
library(reshape2)
volcano3d <- melt(volcano)
colnames(volcano3d) <- c("x", "y", "z")
p <- ggplot(volcano3d, aes(x, y, z = z)) + geom_contour()
py$ggplotly(p)
```
Nope.
## geom_crossbar, linerange, pointrange, and errorbar
```{r crossbar}
# From ggplot example:
# Generate data: means and standard errors of means for prices
# for each type of cut
dmod <- lm(price ~ cut, data=diamonds)
cuts <- data.frame(cut=unique(diamonds$cut), predict(dmod, data.frame(cut = unique(diamonds$cut)), se=TRUE)[c("fit","se.fit")])
# Display estimates and standard errors in various ways
se <- ggplot(cuts, aes(cut, fit,
ymin = fit - se.fit, ymax=fit + se.fit, colour = cut))
se + geom_linerange()
se + geom_pointrange()
se + geom_crossbar()
py$ggplotly(se+geom_linerange())
py$ggplotly(se+geom_pointrange())
py$ggplotly(se+geom_crossbar())
py$ggplotly(se+geom_errorbar())
```
Nope.
## geom_density/2d
```{r density}
p <- ggplot(iris, aes(Sepal.Width, fill=Species, group=Species))
p + geom_density(alpha=0.5)
py$ggplotly(p + geom_density(alpha=0.5))
```
nope.
## geom_dotplot
```{r dotplot}
p + geom_dotplot(binwidth=0.1)
py$ggplotly(p + geom_dotplot(binwidth=0.1))
```
no.
## geom_freqpoly
```{r freqpoly}
p + geom_freqpoly()
py$ggplotly(p + geom_freqpoly())
```
no.
## geom_hex
```{r hex}
p <- ggplot(iris, aes(Sepal.Width, Petal.Length, fill=Species, group=Species))
p + geom_hex()
```
## geom_histogram
```{r hist}
p <- ggplot(iris, aes(Sepal.Width, fill=Species, group = Species))
p + geom_histogram()
py$ggplotly(p+geom_histogram())
```
no.
## geom_jitter
```{r jitter}
p <- ggplot(iris, aes(Petal.Width, Sepal.Length, color = Species))
p + geom_jitter()
py$ggplotly(p+geom_jitter())
#try position instead
py$ggplotly(p + geom_point(position=position_jitter()))
```
geom_jitter fails, but position jitter passed to geompoint seems to work fine.
## geom_line
(potentially the most useless plot ever, but just as an example...)
```{r line}
p <- p + geom_line()
p
```
```{r}
py$ggplotly(p)
```
yes, funny that abline and the other line geoms do not work.
## geom_map
```{r maps}
library(maps)
library(plyr)
texas <- map("county", regions = "texas", plot = FALSE, fill = TRUE)
texas <- fortify(texas)
texas <- ddply(texas, "subregion",
function(df){
mutate(df, fakeIQ = rnorm(1, 80, 15))
}
)
p <- ggplot(texas, aes(x = long, y = lat, group = group, fill = fakeIQ))
p <- p + geom_polygon(colour = "white", size = 0.3)
print(p)
py$ggplotly(p)
library(ggmap)
p <- qmap('Texas', zoom = 6, maptype = 'satellite', legend = 'topleft')
p <- p + geom_polygon(data = texas, aes(x = long, y = lat, group = group, fill = fakeIQ)
, color = 'white', alpha = .75, size = .2)
p <- p + labs(title="IQ scores by county of people who voted for Rick Perry (FAKE DATA) ")
p
```
```{r crimemap}
py$ggplotly(p)
```
no maps.
## geom_path
```{r paths}
# Use the arrow parameter to add an arrow to the line
# See ?grid::arrow for more details
library(grid)
c <- ggplot(economics, aes(x = date, y = pop))
# Arrow defaults to "last"
c + geom_path(arrow = arrow())
py$ggplotly(c + geom_path(arrow = arrow()))
```
success!
## geom_point
Clearly this works.
## geom_polygon
I"m guessing that since the map, which uses polygon, didn't work, this probably won't either. Stolen example from ggplot docs.
```{r poly}
# When using geom_polygon, you will typically need two data frames:
# one contains the coordinates of each polygon (positions), and the
# other the values associated with each polygon (values). An id
# variable links the two together
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)
)
# Currently we need to manually merge the two together
datapoly <- merge(values, positions, by=c("id"))
(p <- ggplot(datapoly, aes(x=x, y=y)) + geom_polygon(aes(fill=value, group=id)))
py$ggplotly(p)
rm(p)
```
Wrong, it works.
##geom_quantile /stat_quantile
```{r quant}
msamp <- movies[sample(nrow(movies), 1000), ]
q10 <- seq(0.05, 0.95, by=0.05)
m <- ggplot(msamp, aes(year, rating)) + geom_point()
m <- m + stat_quantile(aes(colour = ..quantile..), quantiles = q10) +
scale_colour_gradient2(midpoint = 0.5)
m
py$ggplotly(m)
```
no.
## geom_raster
Example taken from ggplot docs
```{r}
# Generate data
pp <- function (n,r=4) {
x <- seq(-r*pi, r*pi, len=n)
df <- expand.grid(x=x, y=x)
df$r <- sqrt(df$x^2 + df$y^2)
df$z <- cos(df$r^2)*exp(-df$r/6)
df
}
raster <- qplot(x, y, data = pp(20), fill = z, geom = "raster")
raster
py$ggplotly(raster)
```
no.
## geom_rect
```{r rect}
df <- data.frame(
x = sample(10, 20, replace = TRUE),
y = sample(10, 20, replace = TRUE)
)
p <- ggplot(df, aes(xmin = x, xmax = x + 1, ymin = y, ymax = y + 2))
p <- p + geom_rect()
p
py$ggplotly(p)
```
No.
## geom_ribbon
```{r ribbon}
msamp <- movies[sample(nrow(movies), 1000), ]
m <- ggplot(msamp, aes(y=log(votes), x=year))
m <- m + geom_point()
m <- m + stat_summary(geom="ribbon", fun.ymin="min", fun.ymax="max")
m
py$ggplotly(m)
```
Points work, stat summary doesn't.
## geom_rug
```{r rug}
msamp <- movies[sample(nrow(movies), 1000), ]
p <- ggplot(msamp, aes(year, log(votes)))
p <- p + geom_point()
(p <- p + geom_rug())
py$ggplotly(p)
```
No.
## geom_segment
example from ggplot docs
```{r seg}
library(grid) # needed for arrow function
p <- ggplot(seals, aes(x = long, y = lat))
p <- p + geom_segment(aes(xend = long + delta_long, yend = lat + delta_lat), arrow = arrow(length = unit(0.1,"cm")))
p
py$ggplotly(p)
```
## geom_smooth
```{r}
p <- ggplot(mtcars, aes(wt, mpg, color = factor(cyl) ))
p <- p + geom_point()
p <- p + geom_smooth()
p
py$ggplotly(p)
```
No smoothing.
## geom_step
Example straight from ggplot docs
```{r step}
# Also works with other aesthetics
df <- data.frame(
x = sort(rnorm(50)),
trt = sample(c("a", "b"), 50, rep = TRUE)
)
p <- qplot(seq_along(x), x, data = df, geom="step", colour = trt)
p
py$ggplotly(p)
```
No.
## geom_text
```{r text}
p <- ggplot(iris, aes(Petal.Width, Sepal.Length, label=Species, colour=Species))
p <- p + geom_point()
p <- p + geom_text(angle=45)
p <- p + geom_text(data = NULL, x = 0.5, y = 7.2, label = "plotly is cool")
p
py$ggplotly(p)
```
No.
## geom_tile
```{r tile}
# Generate data
pp <- function (n,r=4) {
x <- seq(-r*pi, r*pi, len=n)
df <- expand.grid(x=x, y=x)
df$r <- sqrt(df$x^2 + df$y^2)
df$z <- cos(df$r^2)*exp(-df$r/6)
df
}
p <- ggplot(pp(20), aes(x=x,y=y))
p <- p + geom_tile(aes(fill=z))
p
py$ggplotly(p)
```
No.
## geom_violin
```{r vio}
p <- ggplot(mtcars, aes(factor(cyl), wt, fill=factor(cyl)))
p <- p + geom_violin()
p
py$ggplotly(p)
```
No.
## facets
```{r facets}
p <- ggplot(iris, aes(Sepal.Length, Petal.Width, colour=Species, fill=Species))
p <- p + geom_point()
p + facet_wrap(~ Species)
py$ggplotly(p + facet_wrap(~Species))
py$ggplotly(p + facet_grid(~Species))
```
no - it doesn't pick up the facet. Perhaps subplot would work?
```{r subplotDNI, echo=FALSE}
library(ggplot2)
library(maps)
library(plyr)
# getbox by Heike Hoffman,
# https://github.com/ggobi/paper-climate/blob/master/code/maps.r
getbox <- function (map, xlim, ylim) {
# identify all regions involved
small <- subset(map, (long > xlim[1]) & (long < xlim[2]) & (lat > ylim[1]) & (lat < ylim[2]))
regions <- unique(small$region)
small <- subset(map, region %in% regions)
# now shrink all nodes back to the bounding box
small$long <- pmax(small$long, xlim[1])
small$long <- pmin(small$long, xlim[2])
small$lat <- pmax(small$lat, ylim[1])
small$lat <- pmin(small$lat, ylim[2])
# Remove slivvers
small <- ddply(small, "group", function(df) {
if (diff(range(df$long)) < 1e-6) return(NULL)
if (diff(range(df$lat)) < 1e-6) return(NULL)
df
})
small
}
## map layer
## adapted from map_nasa:
# https://github.com/ggobi/paper-climate/blob/master/code/maps.r
# assembling data
world <- map_data("world")
states <- map_data("state")
states$group <- max(world$group) + states$group
both <- rbind(world, states)
americas <- getbox(both, xlim = c(-115, -55), ylim = c(-21.1, 36.6))
# building americas layer
map_americas <- list(
geom_polygon(aes(long, lat, group = group), data = americas, fill = "grey70",
colour = "grey60", inherit.aes = FALSE, show_guide = FALSE),
scale_x_continuous("", breaks = NULL, expand = c(0.02, 0)),
scale_y_continuous("", breaks = NULL, expand = c(0.02, 0)))
# building afghanistan layer
afghanistan <- getbox(world, c(60,75), c(28, 39))
map_afghanistan <- list(
geom_polygon(aes(long, lat, group = group), data = afghanistan,
fill = "grey80", colour = "white", inherit.aes = FALSE,
show_guide = FALSE),
scale_x_continuous("", breaks = NULL, expand = c(0.02, 0)),
scale_y_continuous("", breaks = NULL, expand = c(0.02, 0)))
```
example taken straight from ggsubplot's manual.
```{r subplot}
library(ggsubplot)
library(maps)
data(casualties)
data(mapping)
p <- ggplot(casualties)
p <- p + map_afghanistan
p <- p + geom_subplot2d(aes(lon, lat,
subplot = geom_bar(aes(victim, ..count.., fill = victim))),
bins = c(15,12), ref = NULL, width = rel(0.8))
p <- p + coord_map()
p
py$ggplotly(p)
```
no.
# master list of geoms:
[ggplot2 docs](http://docs.ggplot2.org/current/)
### geoms
* geom_abline() = FALSE
* geom_area() = FALSE
* geom_bar() = FALSE
* geom_bin2d() = FALSE
* geom_blank() =
* geom_boxplot() = FALSE
* geom_contour() = FALSE
* geom_crossbar() = FALSE
* geom_density() = FALSE
* geom_density2d() = FALSE
* geom_dotplot() = FALSE
* geom_errorbar() = FALSE
* geom_errorbarh() = FALSE
* geom_freqpoly() = FALSE
* geom_hex() = Untested
* geom_histogram() = FALSE
* geom_hline() = FALSE
* geom_jitter() = FALSE
* geom_line() = TRUE
* geom_linerange() = FALSE
* geom_map() = FALSE
* geom_path() = TRUE
* geom_point() = TRUE
* geom_pointrange() = FALSE
* geom_polygon() =TRUE
* geom_quantile() = FALSE
* geom_raster() = FALSE
* geom_rect() = FALSE
* geom_ribbon() = FALSE
* geom_rug() = FALSE
* geom_segment() = TRUE
* geom_smooth() = FALSE
* geom_step() = FALSE
* geom_text() = FALSE
* geom_tile() = FALSE
* geom_violin() = FALSE
* geom_vline() = FALSE
### stats
* stat_abline() = FALSE
* stat_bin()
* stat_bin2d()
* stat_bindot()
* stat_bindot()
* stat_binhex()
* stat_contour()
* stat_density()
* stat_density2d()
* stat_ecdf()
* stat_function()
* stat_hline()
* stat_identity()
* stat_qq()
* stat_quantile() = false
* stat_smooth()
* stat_spoke()
* stat_sum()
* stat_summary()
* stat_summary_hex()
* stat_summary2d()
* stat_unique()
* stat_vline()
* stat_ydensity()
### other ggplot stuff
* expand_limits
* guide_legend
* guide_colourbar(guide_colorbar)
* scale_alpha(scale_alpha_continuous, scale_alpha_discrete)
* scale_area()
* scale_color_brewer
* scale_color_continuous
* scale_color_discrete
* scale_color_gradient
* scale_color_gradient2
* scale_color_gradientn
* coord_cartesian
* coord_equal
* coord_fixed
* coord_flip
* coord_map = FALSE
* coord_polar
* coord_trans
*
* facet_grid
* facet_null
* facet_wrap
*
* position_dodge
* position_fill
* position_identity
* position_jitter
* position_stack