Showing posts with label plotly. Show all posts
Showing posts with label plotly. Show all posts

Thursday, November 21, 2024

Day 8: 30-days to learn rgl, plotly, and gganimate - Creating Animated Plots with gganimate and Exporting Frames to Plotly

 


Step 1: Set Up Your Environment

  1. Install Required Packages: Ensure you have the following libraries installed:

install.packages(c("gganimate", "ggplot2", "plotly"))

  1. Load Libraries:

library(gganimate)

library(ggplot2)

library(plotly)


Step 2: Prepare Your Dataset

  1. Use a time-based dataset or create one for practice. For example:

data <- data.frame(

  year = rep(2000:2010, each = 3),

  category = rep(c("A", "B", "C"), times = 11),

  value = runif(33, 10, 100)

)

  1. Preview your dataset:

head(data)


Step 3: Create a Static ggplot

  1. Start by plotting the data without animation:

p <- ggplot(data, aes(x = year, y = value, color = category)) +

  geom_line(aes(group = category)) +

  theme_minimal() +

  labs(title = "Value Trends Over Time", x = "Year", y = "Value")

  1. Print the plot to ensure correctness:

print(p)


Step 4: Animate the Plot with gganimate

  1. Add animation to visualize trends over time:

animated_plot <- p +

  transition_time(year) +

  ease_aes('linear') +

  labs(subtitle = "Year: {frame_time}")

  1. Render the animation in your RStudio viewer:

animate(animated_plot, nframes = 100, fps = 10)

  1. Save the animation as a GIF (optional):

anim_save("animated_plot.gif", animation = animated_plot)

Step 5: Export Frames to Plotly

Here’s a corrected version of how to export frames to Plotly:


  1. Add a Frame Column: Add a frame column to the dataset for use in plot_ly():

data$frame <- data$year

  1. Create a Plotly Animation: Use plot_ly() to build the animated visualization. Explicitly set the trace type to "scatter" and specify the mode:

plotly_animation <- plot_ly(

  data = data,

  x = ~year,

  y = ~value,

  color = ~category,

  frame = ~frame,

  type = "scatter",

  mode = "lines+markers"

) %>%

  layout(

    title = "Interactive Animation with Plotly",

    xaxis = list(title = "Year"),

    yaxis = list(title = "Value")

  )

  1. Render the Plotly Animation: Display the interactive animated plot:

plotly_animation


Sunday, November 17, 2024

Day 7: 30-days to learn rgl, plotly, and gganimate - Combining gganimate and Plotly for added interactivity

 


Step 1: Install Required Libraries

Ensure you have the necessary libraries installed and loaded:

install.packages("ggplot2")
install.packages("gganimate")
install.packages("plotly")
 
library(ggplot2)
library(gganimate)
library(plotly)

Step 2: Create an Animated Plot with gganimate

We’ll first create a simple animated scatter plot showing the movement of points over time.

  1. Prepare the Data:
# Sample data for animation
set.seed(42)
data <- data.frame(
  x = rnorm(50),
  y = rnorm(50),
  time = rep(1:5, each = 10),
  group = rep(letters[1:10], times = 5)
)
  1. Create the Animated Plot:
# Animated scatter plot with gganimate
p <- ggplot(data, aes(x = x, y = y, color = group)) +
  geom_point(size = 4) +
  labs(title = 'Time: {frame_time}', x = 'X-Axis', y = 'Y-Axis') +
  transition_time(time) +
  ease_aes('linear')
 
# Save the animation
anim <- animate(p, nframes = 100, fps = 10, renderer = gifski_renderer())

Step 3: Export Animation Frames

Convert the gganimate frames into individual images that can be used in plotly.

  1. Save Frames:
anim_save("gganimate_frames.gif", animation = anim)

Alternatively, save the individual frames as PNG files:

frame_images <- animate(p, nframes = 100, fps = 10, renderer = file_renderer(dir = "frames", prefix = "frame", overwrite = TRUE))

Step 4: Integrate with plotly for Interactivity

  1. Load Images into plotly: Use plotly to create an interactive slider for the frames.
library(magick)
 
# Load the GIF
frames_gif <- image_read("gganimate_frames.gif")
 
# Extract individual frames
frames_list <- lapply(seq_len(length(frames_gif)), function(i) {
  frame <- image_write(frames_gif[i], format = "png") # Convert frame to PNG format
  list(source = base64enc::dataURI(frame, mime = "image/png")) # Encode as Base64 URI
})
 
# Create the interactive plot
# Create the interactive plot using plotly
plotly_animation <- plot_ly() %>%
  layout(
    sliders = list(list(
      steps = lapply(seq_along(frames_list), function(i) {
        list(
          method = "restyle",
          args = list("images[0].source", frames_list[[i]]$source),
          label = paste("Frame", i)
        )
      })
    ))
  )

# Add the initial image
plotly_animation <- plotly_animation %>%
  add_image(
    source = frames_list[[1]]$source,
    x = 0, y = 0,
    xanchor = "center", yanchor = "middle"
  )


Step 5: Test the Integration

  1. Run the above code to see your animated and interactive plot in the RStudio Viewer or browser.
  2. Experiment with the hover, zoom, and pan features provided by plotly.

Step 6: Reflect and Experiment

  • Experiment with more complex gganimate animations, such as using transition_states() or view_follow().
  • Add custom interactivity in plotly, such as hover text and annotations.
N.B: The code may have some errors. 

Wednesday, November 13, 2024

Day 3: 30-days to learn rgl, plotly, and gganimate - Dive into 3D plotting with plotly, exploring 3D scatter and surface plots, and customizing axes and color scales




Step 1: Set Up for 3D Plotting

1.     Load plotly: Make sure plotly is loaded in your R environment.

library(plotly)

2.     Create Sample Data: Let’s create sample data for our 3D scatter plot and surface plot.

# Data for 3D Scatter Plot
x_scatter <- rnorm(50)
y_scatter <- rnorm(50)
z_scatter <- rnorm(50)
 
# Data for 3D Surface Plot
x_surface <- seq(-10, 10, length.out = 50)
y_surface <- seq(-10, 10, length.out = 50)
z_surface <- outer(x_surface, y_surface, function(x, y) sin(sqrt(x^2 + y^2)))

Step 2: Create a 3D Scatter Plot

1.     Basic 3D Scatter Plot: Use plot_ly() with type = 'scatter3d' to create a basic 3D scatter plot.

scatter3d_plot <- plot_ly(x = ~x_scatter, y = ~y_scatter, z = ~z_scatter, 
                          type = 'scatter3d', mode = 'markers')
scatter3d_plot
    • Explanation:
      • x = ~x_scatter, y = ~y_scatter, and z = ~z_scatter: Set the x, y, and z coordinates.
      • type = 'scatter3d': Specifies a 3D scatter plot.
      • mode = 'markers': Displays only markers (points) in 3D space.

2.     Customize Marker Colors and Sizes:

scatter3d_plot <- plot_ly(x = ~x_scatter, y = ~y_scatter, z = ~z_scatter, 
                          type = 'scatter3d', mode = 'markers',
                          marker = list(size = 5, color = ~z_scatter, colorscale = 'Viridis'))
scatter3d_plot
    • Explanation:
      • size = 5: Adjusts the size of the markers.
      • color = ~z_scatter: Colors markers based on their z values.
      • colorscale = 'Viridis': Applies a color scale to the z values.

Step 3: Create a 3D Surface Plot

1.     Basic 3D Surface Plot: Use plot_ly() with type = 'surface' to create a basic 3D surface plot.

surface_plot <- plot_ly(z = ~z_surface, x = ~x_surface, y = ~y_surface, type = 'surface')
surface_plot
    • Explanation:
      • z = ~z_surface: Sets the height values of the surface.
      • x = ~x_surface and y = ~y_surface: Sets the x and y coordinates for the surface plot.
      • type = 'surface': Specifies a 3D surface plot.

2.     Customize the Surface Plot with a Color Scale:

surface_plot <- plot_ly(z = ~z_surface, x = ~x_surface, y = ~y_surface, 
                        type = 'surface', colorscale = 'Viridis')
surface_plot
    • Explanation:
      • colorscale = 'Viridis': Adds a Viridis color scale, enhancing the visualization of depth.

Step 4: Customize Axes

You can adjust the axis properties to improve the plot’s readability and style.

1.     Customize 3D Scatter Plot Axes:

scatter3d_plot <- scatter3d_plot %>%
  layout(scene = list(xaxis = list(title = "X Axis", backgroundcolor = "lightgrey", gridcolor = "white"),
                      yaxis = list(title = "Y Axis", backgroundcolor = "lightgrey", gridcolor = "white"),
                      zaxis = list(title = "Z Axis", backgroundcolor = "lightgrey", gridcolor = "white")))
scatter3d_plot
    • Explanation:
      • scene: Defines 3D plot layout options, including xaxis, yaxis, and zaxis.
      • title: Sets custom titles for each axis.
      • backgroundcolor and gridcolor: Adjust axis background and grid colors.

2.     Customize 3D Surface Plot Axes:

surface_plot <- surface_plot %>%
  layout(scene = list(xaxis = list(title = "X Axis", color = "blue"),
                      yaxis = list(title = "Y Axis", color = "green"),
                      zaxis = list(title = "Z Axis", color = "red")))
surface_plot

Step 5: Experiment with Different Color Scales

plotly provides several color scales. Try using different ones to see their effects on your plot.

1.     Apply Different Color Scales to the 3D Scatter Plot:

scatter3d_plot <- plot_ly(x = ~x_scatter, y = ~y_scatter, z = ~z_scatter, 
                          type = 'scatter3d', mode = 'markers',
                          marker = list(size = 5, color = ~z_scatter, colorscale = 'Cividis'))
scatter3d_plot

2.     Apply Different Color Scales to the 3D Surface Plot:

surface_plot <- plot_ly(z = ~z_surface, x = ~x_surface, y = ~y_surface, 
                        type = 'surface', colorscale = 'Electric')
surface_plot
    • Other Color Scales:
      • Try color scales like Jet, Bluered, RdBu, YlGnBu, Greens, and Portland to see different effects.

Step 6: Combine All Customizations

Let’s bring everything together to create a polished 3D scatter and 3D surface plot.

Final 3D Scatter Plot with Customizations

final_scatter3d <- plot_ly(x = ~x_scatter, y = ~y_scatter, z = ~z_scatter, 
                           type = 'scatter3d', mode = 'markers',
                           marker = list(size = 5, color = ~z_scatter, colorscale = 'Viridis')) %>%
  layout(scene = list(xaxis = list(title = "X Axis", backgroundcolor = "lightgrey", gridcolor = "white"),
                      yaxis = list(title = "Y Axis", backgroundcolor = "lightgrey", gridcolor = "white"),
                      zaxis = list(title = "Z Axis", backgroundcolor = "lightgrey", gridcolor = "white")))
final_scatter3d

Final 3D Surface Plot with Customizations

final_surface_plot <- plot_ly(z = ~z_surface, x = ~x_surface, y = ~y_surface, 
                              type = 'surface', colorscale = 'Electric') %>%
  layout(scene = list(xaxis = list(title = "X Axis", color = "blue"),
                      yaxis = list(title = "Y Axis", color = "green"),
                      zaxis = list(title = "Z Axis", color = "red")))
final_surface_plot

Summary

Today, you:

  • Learned to create 3D scatter and surface plots using plotly.
  • Customized marker colors and sizes for 3D scatter plots.
  • Applied color scales to enhance visual appeal.
  • Customized axes in 3D space, including titles, colors, and backgrounds.

Next, you’ll build on this knowledge by diving into more complex plot customizations and interactive features to make the plots even more informative.

Tuesday, November 12, 2024

Day 2: 30-days to learn rgl, plotly, and gganimate - Explore plotly customizations: add labels, hover effects, adjust colors, and practice layout modifications

 


Step 1: Set Up the Basic Plot

We’ll start by creating a simple scatter plot that we’ll customize throughout this tutorial.

1.     Create a Sample Dataset:

# Sample data
x <- c(1, 2, 3, 4, 5)
y <- c(10, 15, 13, 17, 20)
labels <- c("A", "B", "C", "D", "E")

2.     Generate the Basic Scatter Plot:

library(plotly)
 
# Basic scatter plot
plot <- plot_ly(x = ~x, y = ~y, type = 'scatter', mode = 'markers')
plot

Step 2: Add Labels

You can add custom labels for each point to provide additional context.

1.     Add Labels as Text:

plot <- plot_ly(x = ~x, y = ~y, text = ~labels, type = 'scatter', mode = 'markers+text') %>%
  layout(title = "Scatter Plot with Labels",
         xaxis = list(title = "X Axis"),
         yaxis = list(title = "Y Axis"))
plot
    • Explanation:
      • text = ~labels: Adds text labels from the labels variable.
      • mode = 'markers+text': Displays both markers and text.

2.     Adjust Text Position:

plot <- plot %>%
  layout(title = "Scatter Plot with Custom Label Positions") %>%
  style(textposition = 'top right')  # Try 'top left', 'bottom right', etc.
plot

Step 3: Add and Customize Hover Effects

Hover effects can be customized to display more detailed information.

1.     Customize Hover Text:

plot <- plot_ly(x = ~x, y = ~y, text = ~paste("Point:", labels, "<br>X:", x, "<br>Y:", y),
                hoverinfo = 'text', type = 'scatter', mode = 'markers') %>%
  layout(title = "Scatter Plot with Customized Hover Text")
plot
    • Explanation:
      • hoverinfo = 'text': Specifies that hover text should come from the text argument.
      • paste() function with <br>: Adds HTML line breaks to format the hover text neatly.

Step 4: Adjust Colors

Colors can make plots visually appealing and help convey information.

1.     Change Marker Colors:

plot <- plot_ly(x = ~x, y = ~y, text = ~labels, type = 'scatter', mode = 'markers',
                marker = list(color = 'blue', size = 10)) %>%
  layout(title = "Scatter Plot with Custom Marker Color")
plot


2.     Add Conditional Colors:

# Set colors based on y values
colors <- c("red", "green", "blue", "orange", "purple")
 
plot <- plot_ly(x = ~x, y = ~y, text = ~labels, type = 'scatter', mode = 'markers',
                marker = list(color = colors, size = 10)) %>%
  layout(title = "Scatter Plot with Conditional Colors")
plot

3.     Use a Color Gradient:

plot <- plot_ly(x = ~x, y = ~y, text = ~labels, type = 'scatter', mode = 'markers',
                marker = list(color = ~y, colorscale = 'Viridis', size = 10)) %>%
  layout(title = "Scatter Plot with Gradient Colors")
plot

Step 5: Customize Layout

plotly offers extensive layout options to adjust axes, titles, legends, and background.

1.     Modify Title and Axis Titles:

plot <- plot %>%
  layout(title = list(text = "Customized Scatter Plot", font = list(size = 20, color = "darkblue")),
         xaxis = list(title = "Custom X Axis", titlefont = list(size = 15, color = "darkred")),
         yaxis = list(title = "Custom Y Axis", titlefont = list(size = 15, color = "darkgreen")))
plot

2.     Customize Legend:

# Adding a legend and customizing its position and appearance
plot <- plot %>%
  layout(showlegend = TRUE, legend = list(x = 1, y = 1, font = list(size = 10, color = "black")))
plot

3.     Change Background Color:

plot <- plot %>%
  layout(plot_bgcolor = 'lightgrey',  # Background color of the plot area
         paper_bgcolor = 'lavender')  # Background color of the paper
plot



Step 6: Combine All Customizations

Let’s put together everything we learned to create a fully customized scatter plot.

plot <- plot_ly(x = ~x, y = ~y, text = ~paste("Label:", labels, "<br>X:", x, "<br>Y:", y),
                hoverinfo = 'text', type = 'scatter', mode = 'markers+text',
                marker = list(color = ~y, colorscale = 'Viridis', size = 15)) %>%
  layout(title = list(text = "Fully Customized Scatter Plot", font = list(size = 22, color = "darkblue")),
         xaxis = list(title = "Custom X Axis", titlefont = list(size = 15, color = "darkred")),
         yaxis = list(title = "Custom Y Axis", titlefont = list(size = 15, color = "darkgreen")),
         plot_bgcolor = 'lightgrey',
         paper_bgcolor = 'lavender',
         legend = list(x = 1, y = 1, font = list(size = 10, color = "black")))
 
plot

Summary

Today, you:

  • Added text labels and customized their position.
  • Created hover text with detailed information and used HTML for formatting.
  • Customized colors, including conditional colors and gradients.
  • Modified layout elements such as titles, axis labels, background color, and legend position.

Next, you’ll practice 3D plotting and explore deeper interactions to make your plots even more dynamic.