Introduction

This document presents an interactive time series plot created with plotly that visualizes the performance of major European stock indices. The chart is built upon the built-in EuStockMarkets dataset in R and displays four distinct indices over time. By incorporating the RColorBrewer package, each index is rendered with a visually appealing and distinct color, enhancing the overall aesthetic and clarity of the visualization. Interactive features provided by plotly allow users to explore the trends and patterns in the data dynamically.

Loading required libraries

library(plotly)
library(RColorBrewer)

Graph construction

# Load the EuStockMarkets dataset (included in R)
data("EuStockMarkets")

# Convert the time series to a data frame and add a time variable
df <- as.data.frame(EuStockMarkets)
df$Time <- as.numeric(time(EuStockMarkets))

# Generate a palette of 4 colors using RColorBrewer (using the "Set1" palette)
pal <- brewer.pal(4, "Set1")

This line initializes an enhanced interactive plot using plotly. It sets up the base plot with the provided data and x-axis variable, preparing the environment to add multiple traces with advanced features—such as custom hover text, dynamic range sliders, and unified hover modes—that improve interactivity and the overall user experience.

# Create an enhanced interactive plot using plotly
fig <- plot_ly(df, x = ~Time) %>%
  add_lines(y = ~DAX, name = "DAX", line = list(color = pal[1], width = 2),
            hoverinfo = "text",
            text = ~paste("DAX:", round(DAX, 2), "<br>Time:", Time)) %>%
  add_lines(y = ~SMI, name = "SMI", line = list(color = pal[2], width = 2),
            hoverinfo = "text",
            text = ~paste("SMI:", round(SMI, 2), "<br>Time:", Time)) %>%
  add_lines(y = ~CAC, name = "CAC", line = list(color = pal[3], width = 2),
            hoverinfo = "text",
            text = ~paste("CAC:", round(CAC, 2), "<br>Time:", Time)) %>%
  add_lines(y = ~FTSE, name = "FTSE", line = list(color = pal[4], width = 2),
            hoverinfo = "text",
            text = ~paste("FTSE:", round(FTSE, 2), "<br>Time:", Time)) %>%
  layout(
    title = "EuStockMarkets - European Stock Indices",
    xaxis = list(
      title = "Time (years)",
      rangeslider = list(visible = TRUE),  # Adds a range slider for dynamic zooming
      zeroline = FALSE
    ),
    yaxis = list(
      title = "Index Value",
      zeroline = FALSE
    ),
    legend = list(x = 0.1, y = 0.9),
    hovermode = "x unified",  # Shows a unified hover label for all traces
    template = "plotly_white"  # Clean and modern theme for the plot
  ) %>%
  config(displayModeBar = TRUE)  # Displays the mode bar for additional interactive tools

Plotly Power

fig