library(plotly)
library(dplyr)
library(knitr)
library(ggplot2)
library(DT)
library(faraway)
library(GGally)
library(ggthemes)
library(gridExtra)
library(dlnm)
library(ggthemes)
library(forcats)
library(RColorBrewer)
library(viridis)
library(readr)
library(ggmap)
library(choroplethr)
library(choroplethrMaps)

Aesthetics of ggplot2

Code Description x Position on x-axis y Position on y-axis shape Shape color Color of border of elements fill Color of inside of elements size Size alpha Transparency (1: opaque; 0: transparent) linetype Type of line (e.g., solid, dashed)

# All geom functions have both required and accepted aesthetics. For example, the geom_point
# function requires x and y, but the function will also accept alpha (transparency), color, fill,
# group, size, shape, and stroke aesthetics.
ggplot(worldcup, aes(x = Time, y = Passes)) +
geom_point()

ggplot(worldcup, aes(x = Time, y = Passes,
color = Position, size = Shots)) +
geom_point()

# Function Common aesthetics Common arguments
# geom_point() x, y
# geom_line() x, y arrow, na.rm
# geom_segment() x, y, xend, yend arrow, na.rm
# geom_path() x, y na.rm
# geom_polygon() x, y
# geom_histogram() x bins, binwidth
# geom_abline() intercept, slope
# geom_hline() yintercept
# geom_vline() xintercept
# geom_smooth() x, y method, se, span
# geom_text() x, y, label parse, nudge_x, nudge_y
# Using multiple geoms

noteworthy_players <- worldcup %>% filter(Shots == max(Shots) |
Passes == max(Passes)) %>%
dplyr::mutate(point_label = paste(Team, Position, sep = ", "))


noteworthy_players
##    Team   Position Time Shots Passes Tackles Saves       point_label
## 1 Ghana    Forward  501    27    151       1     0    Ghana, Forward
## 2 Spain Midfielder  515     4    563       6     0 Spain, Midfielder
ggplot(worldcup, aes(x = Passes, y = Shots)) +
geom_point() +
geom_text(data = noteworthy_players, aes(label = point_label),
vjust = "inward", hjust = "inward")

ggplot(worldcup, aes(x = Time)) +
geom_histogram(binwidth = 10) +
geom_vline(xintercept = 90 * 0:6,
color = "blue", alpha = 0.5)

# Each observation in this dataframe represents a measurement for a child, including some
# physiological measurements like height and weight, and some children were measured
# multiple times and so have multiple observations in this data. Before plotting this data, we
# cleaned it a bit. We used tidyverse functions to select a subset of the columns: child id, sex,
# weight, height, and age. We also used the distinct function from dplyr to limit the dataset to
# the first measurement for each child.


nepali <- nepali %>%
select(id, sex, wt, ht, age) %>%
dplyr::mutate(id = factor(id),
sex = factor(sex, levels = c(1, 2),
labels = c("Male", "Female"))) %>%
distinct(id, .keep_all = TRUE)


head(nepali)
##       id    sex   wt    ht age .keep_all
## 1 120011   Male 12.8  91.2  41      TRUE
## 2 120012 Female 14.9 103.9  57      TRUE
## 3 120021 Female  7.7  70.1   8      TRUE
## 4 120022 Female 12.1  86.4  35      TRUE
## 5 120023   Male 14.2  99.4  49      TRUE
## 6 120031   Male 13.9  96.4  46      TRUE
# Histograms

ggplot(nepali, aes(x = ht)) +
geom_histogram()

ggplot(nepali, aes(x = ht)) +
geom_histogram(fill = "lightblue", color = "black") +
ggtitle("Height of children") +
xlab("Height (cm)") + xlim(c(0, 120))

# Scatterplots
ggplot(nepali, aes(x = ht, y = wt)) +
geom_point(color = "blue", size = 0.5) +
ggtitle("Weight versus Height") +
xlab("Height (cm)") + ylab("Weight (kg)")

ggplot(nepali, aes(x = ht, y = wt, color = sex)) +
geom_point(size = 1) +
ggtitle("Weight versus Height") +
xlab("Height (cm)") + ylab("Weight (kg)")

# Boxplots
ggplot(nepali, aes(x = 1, y = ht)) +
geom_boxplot() +
xlab("")+ ylab("Height (cm)")

ggplot(nepali, aes(x = sex, y = ht)) +
geom_boxplot() +
xlab("Sex")+ ylab("Height (cm)")

# Extensions of ggplot2
library(GGally)
ggpairs(nepali %>% select(sex, wt, ht, age))

data(nepali)
data(worldcup)

data(chicagoNMMAPS)
chic <- chicagoNMMAPS
chic_july <- chic %>%
filter(month == 7 & year == 1995)


# • theme_linedraw
# • theme_bw
# • theme_minimal
# • theme_void
# • theme_dark
# • theme_classic


chicago_plot <- ggplot(chic_july, aes(x = date, y = death)) +
xlab("Day in July 1995") +
ylab("All-cause deaths") +
ylim(0, 450)

chicago_plot +
geom_area(fill = "black") +
theme_excel()

chicago_plot +
geom_line() +
theme_tufte()

library(forcats)
# Create a messier example version of the data


wc_example_data <- worldcup %>%
dplyr::rename(Pos = Position) %>%
dplyr::mutate(Pos = fct_recode(Pos,
"DC" = "Defender",
"FW" = "Forward",
"GK" = "Goalkeeper",
"MF" = "Midfielder"))


wc_example_data %>%
ggplot(aes(x = Pos)) +
geom_bar()

wc_example_data %>%
dplyr::mutate(Pos = fct_recode(Pos,
"Defender" = "DC",
"Forward" = "FW",
"Goalkeeper" = "GK",
"Midfielder" = "MF")) %>%
ggplot(aes(x = Pos)) +
geom_bar(fill = "lightgray") +
xlab("") +
ylab("Number of players") +
coord_flip() +
theme_tufte()

# 
# In this code example, we’ve used the fct_recode function from the forcats package
# to both create the messier example data and also to clean up category names for
# the second plot. The forcats package has a number of useful functions for working
# with factors in R.
#references

ggplot(filter(worldcup, Position == "Forward"), aes(x = Passes, y = Shots)) +
geom_point(size = 1.5) +
theme_few() +
geom_smooth()
## `geom_smooth()` using method = 'loess'

# 
# The most useful geom_smooth parameters to know are:
# • method: The default is to add a loess curve if the data includes less than 1000 points
# and a generalized additive model for 1000 points or more. However, you can change
# to show the fitted line from a linear model using method = "lm" or from a generalized
# linear model using method = "glm".
# • span: How wiggly or smooth the smooth line should be (smaller value: more flexible;
# larger value: more smooth)
# • se: TRUE or FALSE, indicating whether to include shading for 95% confidence intervals.
# • level: Confidence level for confidence interval (e.g., 0.90 for 90% confidence intervals)


# Lines and polygons can also be useful for adding references, as in Figure @ref(fig:referenceexample1).
# Useful geoms for such shapes include:
# • geom_hline, geom_vline: Add a horizontal or vertical line
# • geom_abline: Add a line with an intercept and slope
# • geom_polygon: Add a filled polygon
# • geom_path: Add an unfilled polygon


# You want these references to support the main data shown in the plot, but not overwhelm
# it. When adding these references:
# • Add reference elements first, so they will be plotted under the data, instead of on top
# of it.
# • Use alpha to add transparency to these elements.
# • Use colors that are unobtrusive (e.g., grays).
# • For lines, consider using non-solid line types (e.g., linetype = 3).


worldcup %>%
ggplot(aes(x = Time, y = Shots)) +
geom_point() +
facet_grid(. ~ Position)

worldcup %>%
ggplot(aes(x = Time, y = Shots)) +
geom_point(alpha = 0.25) +
facet_wrap(~ Team, ncol = 6)

nepali <- nepali %>%
dplyr::mutate(sex = factor(sex, levels = c(1, 2),
labels = c("Male", "Female")))


ggplot(nepali, aes(ht, wt)) +
geom_point() +
facet_grid(. ~ sex)
## Warning: Removed 123 rows containing missing values (geom_point).

# Alphabetic order


## Left plot
worldcup %>%
group_by(Team) %>%
dplyr::summarize(mean_time = mean(Time)) %>%
ggplot(aes(x = mean_time, y = Team)) +
geom_point() +
theme_few() +
xlab("Mean time per player (minutes)") + ylab("")

## Ordered
worldcup %>%
group_by(Team) %>%
dplyr::summarize(mean_time = mean(Time)) %>%
arrange(mean_time) %>% # re-order and re-set
dplyr::mutate(Team = factor(Team, levels = Team)) %>% # factor levels before plotting
ggplot(aes(x = mean_time, y = Team)) +
geom_point() +
theme_few() +
xlab("Mean time per player (minutes)") + ylab("")

## Ordered Facets
worldcup %>%
select(Position, Time, Shots) %>%
group_by(Position) %>%
dplyr::mutate(ave_shots = mean(Shots),
most_shots = Shots == max(Shots)) %>%
ungroup() %>%
arrange(ave_shots) %>%
dplyr::mutate(Position = factor(Position, levels = unique(Position))) %>%
ggplot(aes(x = Time, y = Shots, color = most_shots)) +
geom_point(alpha = 0.5) +
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black"),
guide = FALSE) +
facet_grid(. ~ Position) +
theme_few()

worldcup %>%
dplyr::select(Team, Time) %>%
dplyr::group_by(Team) %>%
dplyr::mutate(ave_time = mean(Time),
min_time = min(Time),
max_time = max(Time)) %>%
dplyr::arrange(ave_time) %>%
dplyr::ungroup() %>%
dplyr::mutate(Team = factor(Team, levels = unique(Team))) %>%
ggplot(aes(x = Time, y = Team)) +
geom_segment(aes(x = min_time, xend = max_time, yend = Team),
alpha = 0.5, color = "gray") +
geom_point(alpha = 0.5) +
geom_point(aes(x = ave_time), size = 2, color = "red", alpha = 0.5) +
theme_minimal() +
ylab("")

worldcup %>%
dplyr::select(Team, Time) %>%
dplyr::group_by(Team) %>%
dplyr::mutate(ave_time = mean(Time),
min_time = min(Time),
max_time = max(Time)) %>%
dplyr::ungroup() %>%
dplyr::arrange(ave_time) %>%
dplyr::mutate(Team = factor(Team, levels = unique(Team))) %>%
ggplot(aes(x = Time, y = Team)) +
geom_segment(aes(x = min_time, xend = max_time, yend = Team),
alpha = 0.5, color = "gray") +
geom_point(alpha = 0.5) +
geom_point(aes(x = ave_time), size = 2, color = "red", alpha = 0.5) +
theme_minimal() +
ylab("")

ggplot(worldcup, aes(x = Time, y = Passes, color = Position, size = Shots)) +
geom_point(alpha = 0.5) +
scale_x_continuous(name = "Time played (minutes)",
breaks = 90 * c(2, 4, 6),
minor_breaks = 90 * c(1, 3, 5))

ggplot(worldcup, aes(x = Time, y = Passes, color = Position, size = Shots)) +
geom_point(alpha = 0.5) +
scale_x_continuous(name = "Time played (minutes)",
breaks = 90 * c(2, 4, 6),
minor_breaks = 90 * c(1, 3, 5)) +
scale_size_continuous(name = "Shots on goal",
breaks = c(0, 10, 20))

# Dates

ggplot(chic_july, aes(x = date, y = death)) +
geom_line()

ggplot(chic_july, aes(x = date, y = death)) +
geom_line() +
scale_x_date(name = "Date in July 1995",
date_labels = "%m-%d")

ggplot(chic_july, aes(x = date, y = death)) +
geom_line() +
scale_y_log10(breaks = c(1:4 * 100))

 display.brewer.pal(name = "Set1", n = 8)

 display.brewer.pal(name = "PRGn", n = 8)

 display.brewer.pal(name = "PuBuGn", n = 8)

 wc_example <- ggplot(worldcup, aes(x = Time, y = Passes,
color = Position, size = Shots)) +
geom_point(alpha = 0.5)
a <- wc_example +
scale_color_brewer(palette = "Set1") +
ggtitle("Set1")
b <- wc_example +
scale_color_brewer(palette = "Dark2") +
ggtitle("Dark2")
c <- wc_example +
scale_color_brewer(palette = "Pastel2") +
ggtitle("Pastel2") +
theme_dark()
d <- wc_example +
scale_color_brewer(palette = "Accent") +
ggtitle("Accent")
grid.arrange(a, b, c, d, ncol = 2)

 ggplot(worldcup, aes(x = Time, y = Passes,
color = Position, size = Shots)) +
geom_point(alpha = 0.5) +
scale_color_manual(values = c("blue", "red",
"darkgreen", "darkgray"))

 library(gridExtra)
worldcup_ex <- worldcup %>%
ggplot(aes(x = Time, y = Shots, color = Passes)) +
geom_point(size = 0.9)
magma_plot <- worldcup_ex +
scale_color_viridis(option = "A") +
ggtitle("magma")
inferno_plot <- worldcup_ex +
scale_color_viridis(option = "B") +
ggtitle("inferno")
plasma_plot <- worldcup_ex +
scale_color_viridis(option = "C") +
ggtitle("plasma")
viridis_plot <- worldcup_ex +
scale_color_viridis(option = "D") +
ggtitle("viridis")
grid.arrange(magma_plot, inferno_plot, plasma_plot, viridis_plot, ncol = 2)

Basics of Mapping Creating maps with ggplot2

us_map <- map_data("state")
## Warning: package 'maps' was built under R version 3.3.2
## 
## Attaching package: 'maps'
## The following object is masked from 'package:plyr':
## 
##     ozone
## The following object is masked from 'package:faraway':
## 
##     ozone
head(us_map, 3)
##        long      lat group order  region subregion
## 1 -87.46201 30.38968     1     1 alabama      <NA>
## 2 -87.48493 30.37249     1     2 alabama      <NA>
## 3 -87.52503 30.37249     1     3 alabama      <NA>
# If you plot the points for a couple of state, mapping longitude to the x aesthetic and latitude
# to the y aesthetic, you can see that the points show the outline of the state:


us_map %>%
filter(region %in% c("north carolina", "south carolina")) %>%
ggplot(aes(x = long, y = lat)) +
geom_point()

us_map %>%
filter(region %in% c("north carolina", "south carolina")) %>%
ggplot(aes(x = long, y = lat, group = group)) +
geom_path()

# If you would like to set the color inside each geographic area, you should use a polygon
# geom rather than a path geom. You can then use the fill aesthetic to set the color inside the
# polygon and the color aesthetic to set the color of the border. For example, to set the interior
# of the states to blue and the borders to black, you can run:
us_map %>%
filter(region %in% c("north carolina", "south carolina")) %>%
ggplot(aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "lightblue", color = "black")

# To get rid of the x- and y-axes and the background grid, you can add the “void” theme to the
# ggplot output:
us_map %>%
filter(region %in% c("north carolina", "south carolina")) %>%
ggplot(aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "lightblue", color = "black") +
theme_void()

# To extend this code to map the full continental U.S., just remove the line of the pipe chain
# that filtered the state mapping data to North and South Carolina:
us_map %>%
ggplot(aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "lightblue", color = "black") +
theme_void()

# In the previous few graphs, we used a constant aesthetic for the fill color. However, you can
# map a variable to the fill to create a choropleth map with a ggplot object. For example, the
# votes.repub dataset in the maps package gives some voting data by state and year:

data(votes.repub)
head(votes.repub)
##             1856  1860  1864  1868  1872  1876  1880  1884  1888  1892
## Alabama       NA    NA    NA 51.44 53.19 40.02 36.98 38.44 32.28  3.95
## Alaska        NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
## Arizona       NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
## Arkansas      NA    NA    NA 53.73 52.17 39.88 39.55 40.50 38.07 32.01
## California 18.77 32.96 58.63 50.24 56.38 50.88 48.92 52.08 49.95 43.76
## Colorado      NA    NA    NA    NA    NA    NA 51.28 54.39 55.31 41.13
##             1896  1900  1904  1908  1912  1916  1920  1924  1928  1932
## Alabama    28.13 34.67 20.65 24.38  8.26 21.97 30.98 27.01 48.49 14.15
## Alaska        NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
## Arizona       NA    NA    NA    NA 12.74 35.37 55.41 41.26 57.57 30.53
## Arkansas   25.11 35.04 40.25 37.31 19.73 28.01 38.73 29.28 39.33 12.91
## California 49.13 54.48 61.90 55.46  0.58 46.26 66.24 57.21 64.70 37.40
## Colorado   13.84 42.04 55.27 46.88 21.88 34.75 59.32 57.02 64.72 41.43
##             1936  1940  1944  1948  1952  1956  1960 1964 1968 1972  1976
## Alabama    12.82 14.34 18.20 19.04 35.02 39.39 41.75 69.5 14.0 72.4 43.48
## Alaska        NA    NA    NA    NA    NA    NA 50.94 34.1 45.3 58.1 62.91
## Arizona    26.93 36.01 40.90 43.82 58.35 60.99 55.52 50.4 54.8 64.7 58.62
## Arkansas   17.86 20.87 29.84 21.02 43.76 45.82 43.06 43.9 30.8 68.9 34.97
## California 31.70 41.35 42.99 47.14 56.39 55.40 50.10 40.9 47.8 55.0 50.89
## Colorado   37.09 50.92 53.21 46.52 60.27 59.49 54.63 38.7 50.5 62.6 55.89
as.data.frame(votes.repub) %>%tbl_df() %>%
dplyr::mutate(state = rownames(votes.repub),
state = tolower(state)) %>%
right_join(us_map, by = c("state" = "region")) %>%
ggplot(aes(x = long, y = lat, group = group, fill = `1976`)) +
geom_polygon(color = "black") +
theme_void() +
scale_fill_viridis(name = "Republican\nvotes (%)")

serial <- read_csv(paste0("https://raw.githubusercontent.com/",
"dgrtwo/serial-ggvis/master/input_data/",
"serial_podcast_data/serial_map_data.csv"))
## Parsed with column specification:
## cols(
##   x = col_integer(),
##   y = col_integer(),
##   Type = col_character(),
##   Name = col_character(),
##   Description = col_character()
## )
head(serial, 3)
## Source: local data frame [3 x 5]
## 
##       x     y      Type  Name Description
##   (int) (int)     (chr) (chr)       (chr)
## 1   356   437 cell-site  L688          NA
## 2   740   360 cell-site  L698          NA
## 3   910   340 cell-site  L654          NA
serial <- serial %>%
dplyr::mutate(long = -76.8854 + 0.00017022 * x,
lat = 39.23822 + 1.371014e-04 * y,
tower = Type == "cell-site")
serial %>%
slice(c(1:3, (n() - 3):(n())))
## Source: local data frame [7 x 8]
## 
##       x     y          Type                            Name
##   (int) (int)         (chr)                           (chr)
## 1   356   437     cell-site                            L688
## 2   740   360     cell-site                            L698
## 3   910   340     cell-site                            L654
## 4   960   830 base-location Campfield Early Learning Center
## 5   580  1230 base-location               Owings Mills Mall
## 6   720   496 base-location                   Adnan's house
## 7   954   410 base-location                    Jenn's house
## Variables not shown: Description (chr), long (dbl), lat (dbl), tower (lgl)
maryland <- map_data('county', region = 'maryland')
head(maryland)
##        long      lat group order   region subregion
## 1 -78.64992 39.53982     1     1 maryland  allegany
## 2 -78.70148 39.55128     1     2 maryland  allegany
## 3 -78.74159 39.57420     1     3 maryland  allegany
## 4 -78.75878 39.58566     1     4 maryland  allegany
## 5 -78.74732 39.61430     1     5 maryland  allegany
## 6 -78.74732 39.63149     1     6 maryland  allegany
baltimore <- maryland %>%
filter(subregion %in% c("baltimore city", "baltimore"))
head(baltimore, 3)
##        long      lat group order   region subregion
## 1 -76.88521 39.35074     3   114 maryland baltimore
## 2 -76.89094 39.37939     3   115 maryland baltimore
## 3 -76.88521 39.40804     3   116 maryland baltimore
ggplot(baltimore, aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "lightblue", color = "black") +
theme_void()

ggplot(baltimore, aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "lightblue", color = "black") +
geom_point(data = serial, aes(group = NULL, color = tower)) +
theme_void() +
scale_color_manual(name = "Cell tower", values = c("black", "red"))

vvv<-as.data.frame(votes.repub)


vvv %>%tbl_df() %>%

dplyr::mutate(state = rownames(votes.repub), state = tolower(state)) %>%
right_join(us_map, by = c("state" = "region")) %>%
ggplot(aes(x = long, y = lat, group = group, fill = `1976`)) +
geom_polygon(color = "black") +
theme_void() +
scale_fill_viridis(name = "Republican\nvotes (%)")

ggmap Google Maps API

beijing <- get_map("Beijing", zoom = 12)
ggmap(beijing)

# While the default source for maps with get_map is Google Maps, you can also use the function
# to pull maps from OpenStreetMap and Stamen Maps. Further, you can specify the type of
# map, which allows you to pull a variety of maps including street maps and terrain maps.
# You specify where to get the map using the source parameter and what type of map to use
# with the maptype parameter.
# Here are example maps of Estes Park, in the mountains of Colorado, pulled using different
# map sources and map types. Also, note that we’ve used the option extent = "device" when
# calling ggmap, which specifies that the map should fill the whole plot area, instead of leaving
# room for axis labels and titles. Finally, as with any ggplot object, we can save each map to an
# object. We do that here so we can plot them together using the grid.arrange function, which
# we’ll describe in more detail in a later section in this course.


map_1 <- get_map("Estes Park", zoom = 12,
source = "google", maptype = "terrain") %>%
ggmap(extent = "device")
map_2 <- get_map("Estes Park", zoom = 12,
source = "stamen", maptype = "watercolor") %>%
ggmap(extent = "device")
map_3 <- get_map("Estes Park", zoom = 12,
source = "google", maptype = "hybrid") %>%
ggmap(extent = "device")

grid.arrange(map_1, map_2, map_3, nrow = 1)

get_map("Baltimore County", zoom = 10,
source = "stamen", maptype = "toner") %>%
ggmap() +
geom_polygon(data = baltimore, aes(x = long, y = lat, group = group),
color = "navy", fill = "lightblue", alpha = 0.2) +
geom_point(data = serial, aes(x = long, y = lat, color = tower)) +
theme_void() +
scale_color_manual(name = "Cell tower", values = c("black", "red"))

# You can use the ggmap package to do a number of other interesting tasks related to geographic
# data. For example, the package allows you to use the Google Maps API, through the geocode
# function, to get the latitude and longitude of specific locations based on character strings of
# the location or its address. For example, you can get the location of the Supreme Court of
# the United States by calling:
geocode("Supreme Court of the United States")
##         lon      lat
## 1 -77.00444 38.89064
# You could also get its location by calling its address:
geocode("1 First St NE, Washington, DC")
##         lon      lat
## 1 -77.00465 38.89051
# You can compute map distances, too, using the mapdist function with two locations:

mapdist("Baltimore, MD",
"1 First St NE, Washington, DC") %>%
select(from, to, miles)
##            from                            to    miles
## 1 Baltimore, MD 1 First St NE, Washington, DC 37.90664

Mapping US counties and states

library(choroplethr)
library(choroplethrMaps)
data(df_pop_county)
df_pop_county %>% slice(1:3)
##   region  value
## 1   1001  54590
## 2   1003 183226
## 3   1005  27469
county_choropleth(df_pop_county)

#If you want to only plot some of states, you can use the state_zoom argument:
county_choropleth(df_pop_county, state_zoom = c("colorado", "wyoming"))

# To plot values over a reference map from Google Maps, you can use the reference_map
# argument:
county_choropleth(df_pop_county, state_zoom= c("north carolina"),
reference_map = TRUE)

HTML Widgets

plot_ly(worldcup, type = "scatter",
x = ~ Time, y = ~ Shots, color = ~ Position)
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
plot_ly(worldcup, type = "scatter",
x = ~ Time, y = ~ Shots, color = I("blue"))
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode
worldcup %>%
dplyr::mutate(Name = rownames(worldcup)) %>%
plot_ly(x = ~ Time, y = ~ Shots, color = ~ Position) %>%
add_markers(text = ~ Name, hoverinfo = "text")
worldcup %>%
dplyr::mutate(Name = rownames(worldcup)) %>%
plot_ly(x = ~ Time, y = ~ Shots, color = ~ Position) %>%
add_markers(text = ~ paste("<b>Name:</b> ", Name, "<br />",
"<b>Team:</b> ", Team),
hoverinfo = "text")
worldcup %>%
plot_ly(x = ~ Time, y = ~ Shots, z = ~ Passes,
color = ~ Position, size = I(3)) %>%
add_markers()
class(volcano)
## [1] "matrix"
plot_ly(z = ~ volcano, type = "surface")
worldcup_scatter <- worldcup %>%
ggplot(aes(x = Time, y = Shots, color = Position)) +
geom_point()
ggplotly(worldcup_scatter)