To achieve separate scaling for the left and right y-axes in your ggplot, you'll need to manually scale the futures (FUT_1_mean and FUT_2_mean) to align with the basis variables (DEC_BASIS_mean, PEO_BASIS_mean, ESL_BASIS_mean). This allows each set of variables to retain their own min and max values on their respective axes.
Here's a step-by-step guide to accomplish this:
-
Calculate the Range for Each Y-Axis:
-
Determine the Scaling Transformation:
To overlay the futures variables onto the same plot as the basis variables, you need to scale them appropriately. The scaling factor (scale_factor) and offset (offset) are calculated to map the futures' range to the basis' range.
[
\text{scale_factor} = \frac{\text{basis_max} - \text{basis_min}}{\text{fut_max} - \text{fut_min}}
]
[
\text{offset} = \text{basis_min} - (\text{fut_min} \times \text{scale_factor})
]
-
Update the ggplot:
-
Plot Basis Variables: These are plotted normally on the left y-axis.
-
Plot Futures Variables: These are scaled using the scale_factor and offset, then plotted on the same graph. The secondary y-axis is then defined using the inverse of this transformation to display the original futures scale.
-
Complete Code Implementation:
# Load necessary libraries
library(ggplot2)
library(gridExtra)
# Assuming Weekly_avg is your dataframe and it's already loaded
# Step 1: Calculate min and max for each set of variables
basis_min <- min(c(Weekly_avg$DEC_BASIS_mean, Weekly_avg$PEO_BASIS_mean, Weekly_avg$ESL_BASIS_mean), na.rm = TRUE)
basis_max <- max(c(Weekly_avg$DEC_BASIS_mean, Weekly_avg$PEO_BASIS_mean, Weekly_avg$ESL_BASIS_mean), na.rm = TRUE)
fut_min <- min(c(Weekly_avg$FUT_1_mean, Weekly_avg$FUT_2_mean), na.rm = TRUE)
fut_max <- max(c(Weekly_avg$FUT_1_mean, Weekly_avg$FUT_2_mean), na.rm = TRUE)
# Step 2: Calculate scaling factors
scale_factor <- (basis_max - basis_min) / (fut_max - fut_min)
offset <- basis_min - (fut_min * scale_factor)
# Step 3: Create the combined plot
combined_plot <- ggplot(Weekly_avg, aes(x = Period_WEEK)) +
# Plot Basis Variables on Primary Y-Axis (Left)
geom_line(aes(y = DEC_BASIS_mean, color = "DEC_BASIS_mean")) +
geom_line(aes(y = PEO_BASIS_mean, color = "PEO_BASIS_mean")) +
geom_line(aes(y = ESL_BASIS_mean, color = "ESL_BASIS_mean")) +
geom_point(aes(y = DEC_BASIS_mean, color = "DEC_BASIS_mean")) +
geom_point(aes(y = PEO_BASIS_mean, color = "PEO_BASIS_mean")) +
geom_point(aes(y = ESL_BASIS_mean, color = "ESL_BASIS_mean")) +
# Plot Futures Variables on Secondary Y-Axis (Right) with Scaling
geom_line(aes(y = FUT_1_mean * scale_factor + offset, color = "FUT_1_mean"), linetype = "dashed") +
geom_line(aes(y = FUT_2_mean * scale_factor + offset, color = "FUT_2_mean"), linetype = "dashed") +
geom_point(aes(y = FUT_1_mean * scale_factor + offset, color = "FUT_1_mean"), shape = 17) +
geom_point(aes(y = FUT_2_mean * scale_factor + offset, color = "FUT_2_mean"), shape = 17) +
# Labels and Theme
labs(
title = "Basis and Futures Variables Over Weeks",
x = "Period Week",
y = "Basis Mean Value",
color = "Variables"
) +
theme_minimal(base_size = 14) +
theme(
legend.title = element_blank(),
legend.position = "bottom",
legend.key.size = unit(1.5, "lines"),
axis.title = element_text(face = "bold"),
axis.text = element_text(size = 12)
) +
# Define Primary and Secondary Y-Axis
scale_y_continuous(
limits = c(basis_min, basis_max),
sec.axis = sec_axis(~ (. - offset) / scale_factor, name = "Futures Mean Value")
) +
# Customize X-Axis to Show All Weeks
scale_x_continuous(
breaks = seq(
floor(min(Weekly_avg$Period_WEEK, na.rm = TRUE)),
ceiling(max(Weekly_avg$Period_WEEK, na.rm = TRUE)),
by = 1
)
) +
# Define Colors Manually (Optional for Clarity)
scale_color_manual(
values = c(
"DEC_BASIS_mean" = "blue",
"PEO_BASIS_mean" = "green",
"ESL_BASIS_mean" = "red",
"FUT_1_mean" = "purple",
"FUT_2_mean" = "orange"
)
)
# Step 4: Display the Plot
print(combined_plot)
Explanation of the Code:
Final Output:
The resulting plot will display:
-
Left Y-Axis: Represents the basis variables (DEC_BASIS_mean, PEO_BASIS_mean, ESL_BASIS_mean) with their original min and max values.
-
Right Y-Axis: Represents the futures variables (FUT_1_mean, FUT_2_mean) with their original min and max values, scaled appropriately.
Each set of variables is clearly distinguishable through different colors and line types (solid for basis and dashed for futures), and the dual y-axes provide a clear comparison between the two datasets over the weeks.
Additional Tips:
-
Handling Missing Values: Ensure that your data doesn't contain NA values, or handle them appropriately to avoid errors during plotting.
-
Dynamic Scaling: If your dataset updates frequently, consider encapsulating the scaling calculations into functions or using dynamic methods to automatically adjust the scaling parameters.
By following this approach, you can effectively visualize two different datasets with distinct scales on the same plot, maintaining clarity and accuracy in your data representation.