#Gráficos interactivos #Extraido de Interactive charts https://www.r-graph-gallery.com/interactive-charts.html library(ggplot2) install.packages("plotly") library(plotly) install.packages("gapminder") library(gapminder) p <- gapminder %>% filter(year==1977) %>% ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) + geom_point() + theme_bw() p ggplotly(p) head(gapminder) #agregándole texto al popup p <- gapminder %>% filter(year==1977) %>% ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent, aux=country, aux2=year)) + geom_point() + theme_bw() p ggplotly(p) #Otra forma de agregándole texto al popup, esta vez con etiqueta variables p <- gapminder %>% filter(year==1977) %>% ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) + geom_point(aes(text=sprintf("Año: %i
País: %s", year, country))) + theme_bw() ggplotly(p) # p <- ggplot(mtcars, aes(x = disp, y= am, color = as.factor(cyl),gear=gear, hp=hp, vsqwe = vs)) + geom_point() ggplotly(p) ggplotly(p,tooltip = c( "x", "vsqwe", "gear", "hp")) #======= #Gráficos animados #Extraido de https://www.r-graph-gallery.com/271-ggplot2-animated-gif-chart-with-gganimate.html # Get data: library(gapminder) # Charge libraries: library(ggplot2) install.packages("gganimate") library(gganimate) install.packages('Rcpp') library(Rcpp) # Make a ggplot, but add frame=year: one image per year p<-ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) + geom_point() + scale_x_log10() + theme_bw() + # gganimate specific bits: labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') + transition_time(year) + ease_aes('linear') # Save at gif: animate(p) anim_save("271-ggplot2-animated-gif-chart-with-gganimate1.gif") ##================= Extraido de https://plotly.com/ggplot2/animations/ #Con slider library(plotly) library(gapminder) p <- ggplot(gapminder, aes(gdpPercap, lifeExp, color = continent)) + geom_point(aes(size = pop, frame = year, ids = country)) + scale_x_log10() fig <- ggplotly(p) fig #extraido de https://plotly-r.com/improving-ggplotly.html#fig:ggplotly-rangeslider #install.packages("babynames") library(babynames) nms <- filter(babynames, name %in% c("Sam", "Alex")) #las observaciones cuyos nombres sean Sam y Alex p <- ggplot(nms) + geom_line(aes(year, prop, color = sex, linetype = name)) p ggplotly(p, dynamicTicks = TRUE) %>% rangeslider() %>% layout(hovermode = "x unified") #layout(hovermode = "x") #layout() #geom_smooth hecho interactivo con ggplotly p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + geom_smooth() ggplotly(p) %>% layout(hovermode = "x unified") #muestra todos los datos para un x dado p %>% ggplotly(layerData = 2, originalData = FALSE) %>% add_fun(function(p) { p %>% slice(which.max(se)) %>% add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>% add_annotations("Maximum uncertainty", ax = 60) }) %>% add_fun(function(p) { p %>% slice(which.min(se)) %>% add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>% add_annotations("Minimum uncertainty") }) ##curvas de nivel interactivas con geom_density2d() p <- ggplot(MASS::geyser, aes(x = waiting, y = duration)) + geom_density2d() ggplotly(p, originalData = FALSE) %>% group_by(piece) %>% slice(which.min(y)) %>% add_text( text = ~level, size = I(16), color = I("black"), hoverinfo="none" ) #=============================== ###organizando vistas ##vistas independientes en una misma ventana library(plotly) p1 <- plot_ly(economics, x = ~date, y = ~unemploy) %>% add_lines(name = "unemploy") p2 <- plot_ly(economics, x = ~date, y = ~uempmed) %>% add_lines(name = "uempmed") subplot(p1, p2) ##vistas dependientes: comparten el eje x pero tienen diferentes ejes y vars <- setdiff(names(economics), "date") plots <- lapply(vars, function(var) { plot_ly(economics, x = ~date, y = as.formula(paste0("~", var))) %>% add_lines(name = var) }) subplot(plots, nrows = length(plots), shareX = TRUE, titleX = FALSE) # dibujar valores aleatorios correlacionados por una distribución normal bi-variada s <- matrix(c(1, 0.3, 0.3, 1), nrow = 2) m <- mvtnorm::rmvnorm(1e5, sigma = s) x <- m[, 1] #genero los x y <- m[, 2] #genero los y s <- subplot( plot_ly(x = x, color = I("black")), plotly_empty(), plot_ly(x = x, y = y, color = I("black")) %>% add_histogram2dcontour(colorscale = "Viridis"), plot_ly(y = y, color = I("black")), nrows = 2, heights = c(0.2, 0.8), widths = c(0.8, 0.2), margin = 0, shareX = TRUE, shareY = TRUE, titleX = FALSE, titleY = FALSE ) layout(s, showlegend = FALSE) ##con mapas interactividad # specify some map projection/options g <- list( scope = 'usa', projection = list(type = 'albers usa'), lakecolor = toRGB('white') ) # crear un mapa de la densidad de población. Los datos vienen del data.frame "state.x77" density <- state.x77[, "Population"] / state.x77[, "Area"] map <- plot_geo( z = ~density, text = state.name, locations = state.abb, locationmode = 'USA-states' ) %>% layout(geo = g) # create a bunch of horizontal bar charts vars <- colnames(state.x77) barcharts <- lapply(vars, function(var) { plot_ly(x = state.x77[, var], y = state.name) %>% add_bars(orientation = "h", name = var) %>% layout(showlegend = FALSE, hovermode = "y", yaxis = list(showticklabels = FALSE)) }) subplot(barcharts, margin = 0.01) %>% subplot(map, nrows = 2, heights = c(0.3, 0.7), margin = 0.1) %>% layout(legend = list(y = 1)) %>% colorbar(y = 0.5) ###=============== Gráficos interactivos 3D ============ # library library(rgl) # This is to output a rgl plot in a rmarkdown document. setupKnitr() # Data: the iris data is provided by R data <- iris # Add a new column with color mycolors <- c('royalblue1', 'darkcyan', 'oldlace') data$color <- mycolors[ as.numeric(data$Species) ] # Plot plot3d( x=data$`Sepal.Length`, y=data$`Sepal.Width`, z=data$`Petal.Length`, col = data$color, type = 's', radius = .1, xlab="Sepal Length", ylab="Sepal Width", zlab="Petal Length") head(data) install.packages('htmlwidgets') # To display in an R Markdown document: rglwidget() # To save to a file: htmlwidgets::saveWidget(rglwidget(width = 520, height = 520), file = "HtmlWidget/3dscatter.html", libdir = "libs", selfcontained = FALSE) ##======================================================================= ###Esquisse https://cran.r-project.org/web/packages/esquisse/readme/README.html install.packages("esquisse") library(esquisse) esquisse:::esquisser(mpg) #esquisse:::esquisser() #o sin un data.frame de entrada