Created
November 6, 2017 23:42
-
-
Save rer145/f597d42a654b70559abcecda2030786e to your computer and use it in GitHub Desktop.
How to create interactive plots with ggplot2 and R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(Lahman) | |
library(dplyr) | |
library(ggplot2) | |
library(ggiraph) | |
# Get all teams from 1980 and the number of home runs hit | |
df<-Teams %>% | |
filter(yearID == 1980) %>% | |
select(name, HR) %>% | |
arrange(HR) | |
# It is useful to convert a column to a factor, so ggplot can order the results better | |
# Here we are converting the 'name' column to a factor | |
df$name<-factor(df$name, levels=df$name) | |
# Create a normal bar chart plot but making it interactive, we have to store it first | |
g<-ggplot()+ | |
geom_bar_interactive(data=df,aes(x=name,y=HR,tooltip=HR,data_id=name), stat="identity", color="blue", fill="white")+ | |
ggtitle("HR by team in 1980 with ggiraph")+ | |
coord_flip()+ | |
ylab("Homeruns")+ | |
xlab("Team") | |
# Now with ggiraph we can make the hover action change colors | |
ggiraph(code=print(g),hover_css="fill:blue; stroke:white") | |
# The same can be with done with a timeseries plot or line chart. | |
# Here we plot Babe Ruth's home run totals throughout the years | |
# Obtain the data using dplyr | |
df<-Batting %>% | |
filter(playerID=='ruthba01')%>% | |
select(yearID, HR) | |
# Create a plot with both a line chart and point chart combined | |
g<-ggplot()+ | |
geom_line_interactive(data=df,aes(x=yearID,y=HR))+ | |
geom_point_interactive(data=df,aes(x=yearID,y=HR,tooltip=HR,data_id=yearID))+ | |
ggtitle("Babe Ruth HR by year")+ | |
xlab("Year")+ | |
ylab("Home Runs") | |
# Add interactivity with ggiraph | |
ggiraph(code=print(g),hover_css="fill:white;stroke:#336699") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment