Problem 1 [20 points]

Create a plotly graph of your choosing that represents at least two variables, one of which must be a categorical variable.

This plot can be a scatter plot, overlayed density plots (graphing variable is continuous, separate densities grouped by categorical variable), etc. choropleth maps could also be on the list…you have to admit they look kinda cool.

You can use any data of your choosing, just reference this.

The graph must include:

  1. customized hover text that is informative to the graphing elements in the plot

  2. separate color to represent groups

  3. labeled axes and appropriate title

Include at least a 1-paragraph discussion about the graph. Discuss what is being plotted and what information is being displayed in the graph. Discuss any information that the reader may gain from hovering the cursor over graphing elements. Discuss any issues/chalenges you had (if any) while making the plot, and you you dealt with or overcame them.

Solution:

# Check if the package is installed

if (!require("ggplot2")) {
  # Install the package if it's not already installed
  install.packages("ggplot2")
}

if (!require("plotly")) {
  # Install the package if it's not already installed
  install.packages("plotly")
}

# Load library
library(ggplot2)
library(plotly)

# Load mtcars dataset
data(mtcars)

plot_ly(data = mtcars, x = ~wt, y = ~mpg,
         color= ~factor(gear),
                hoverinfo = "text",
                text = ~paste("Car Model: ", rownames(mtcars), "<br>",
                              "Gear: ", gear, "<br>",
                               "Weight: ", wt, "<br>",
                              "Miles Per Gallon: ", mpg),
                type = "scatter", 
                mode = "markers",
                marker = list(size = 15)
         ) %>%
   
layout(title = "Weight vs. Miles Per Gallon",
                 xaxis = list(title = "Wight"),
                 yaxis = list(title = "Miles Per Gallon"),
                 legend = list(title = list(text = "Gear"))
               )

For this task, I chose the “mtcars” dataset, which is available in R. It contains information about different attributes of car models. I selected “wt” (weight) and “mpg” (miles per gallon) as continuous variables, and “gear” as a categorical variable.

The above scatter plot shows the relationship between weight (X-axis) and miles per gallon (Y-axis) for different gear categories. Each data point represents a car model from the mtcars dataset, colored according to the gear category (3, 4, or 5 gears). Hovering over a data point reveals four different pieces of information: the car model, gear category, weight, and mpg. This facilitates insights into the relationship between car weight, mpg, and gear category, and enables the identification of specific car models.

One challenge encountered while creating the plot was ensuring that the hover text displayed the desired information correctly. This was overcome by properly formatting the hover text using the text parameter in the plot_ly function. Additionally, ensuring that the legend title displayed correctly required specifying the title text within the legend parameter in the layout function. As a result, the graph effectively visualizes the relationship between car weight and mpg while providing detailed information on individual data points upon hover.

Problem 2 [20 points]

Create an animated plotly graph with a data set of your choosing. This can be, but does not have to be a scatter plot. Also, the animation does not have to take place over time. As mentioned in the notes, the frame can be set to a categorical variable. However, the categories the frames cycle through should be organized (if needs be) such that the progression through them shows some pattern.

This graph should include:

  1. Aside from the graphing variable, a separate categorical variable. For example, in our animated scatter plot we color grouped the points by continent.

  2. Appropriate axis labels and a title

  3. Augment the frame label to make it more visible. This can include changing the font size and color to make it stand out more, and/or moving the frame label to a new location in the plotting region. Note, if you do this, make sure it is till clearly visible and does not obstruct the view of your plot.

Include at least a 1-paragraph discussion about the plot. Discuss what you are plotting and what trends can be seen throughout the animation. Discuss any issues, if any, you ran into in making the plot and how you overcame them.

Solution:

if (!require("lubridate")) {
  # Install the package if it's not already installed
  install.packages("lubridate")
}
## Loading required package: lubridate
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
if (!require("readxl")) {
  # Install the package if it's not already installed
  install.packages("readxl")
}
## Loading required package: readxl
library(lubridate)
library("readxl")

# Imported data from https://www.nasdaq.com/market-activity/quotes/historical website
# into a data frame and labeled it myData
myData <- read_excel("HistoricalData.xlsx")
#view(myData)

# in this dataset, max value of Volume column is 136682600 (or 1e8)
# Calculate the scaling factor
max(myData$Volume)
## [1] 136682600
min(myData$Volume)
## [1] 24048340
scaling_factor <- 1e-8

# Apply scaling to the Volume column
myData$xData <- myData$Volume * scaling_factor
myData$ydata <- myData$`Close/Last`

# formatted date to extract the months 
date <- as.POSIXct(myData$Date, format = "%m/%d/%Y")
myData$months <- format(date, format="%B")

# Scatter Plots over Different Months
myData %>%
      plot_ly(x = ~xData, y = ~ydata, 
                hoverinfo = "text",
                text = ~paste("Month: ", months, "<br>",
                                "Volume: ", xData, "<br>",
                              "Closing Price: ", `Close/Last`),
                showlegend=FALSE
                 
            ) %>%
  
      animation_opts(frame = 2400, 
                     transition = 2000,
                     easing = "back"
                    ) %>%

      add_text(x = 1.1, y = 187, text = ~months, frame = ~months,
                 textfont = list(size = 50, color = toRGB("grey80"))
               ) %>%
  
      add_markers(frame = ~months,
                  ids = ~Date,
                  size = ~xData, color = ~Low,
                  marker = list(sizemode = "diameter",
                                sizeref=2)
                 ) %>%
         
      layout(title = "Volume vs Closing Price",
                      xaxis = list(title = "Volume"),
                      yaxis = list(title = "Closing Price")
            ) %>%
  
      animation_slider(currentvalue = list(font = list(color="white")),
                         bgcolor = "skyblue" ,
                         font = list(color = "blue",  # Customize label color
                         family = "Arial" ) # Customize label font family
                       )

For this task, I imported data from the website https://www.nasdaq.com/market-activity/quotes/historical and used it as a dataset. It contains information about daily historical stock prices and volumes for each stock. I selected “Volume” and “Closing Prices” as continuous variables and extracted the months from the Date column to use as a categorical variable.

The above scatter plot shows the relationship between Volume (X-axis) and Closing Price (Y-axis) across different month categories. Each data point represents this relationship throughout the animation and is colored based on the low stock price in the dataset. Each frame of the animation corresponds to a different month, depicting how the volume and closing price change over time. Hovering over a data point reveals three pieces of information: Month, Volume, and Closing Price, providing viewers with insights into specific data points.

One challenge encountered while creating the plot was ensuring that the animation ran smoothly and clearly conveyed the trends over time. This was overcome by adjusting the animation options, such as the frame duration, transition duration, and easing value in the plot_ly function. Additionally, I ensured that the legend title displayed correctly based on the low values of the stock price column from the dataset. Moreover, customizing the animation slider, such as changing its background color and font style, could enhance the overall aesthetics and readability of the plot.

** RPubs webpage url:https://rpubs.com/txsst/1175085**