Question:
I’m trying to create a plot in ggplot2 with an arrow line pointing outward, and positioned beneath the x-axis. I used geom_segment function in ggplot2, but its drawing over the plot. I’m want this line with an arrow pointing to the right, positioned below the x-axis, labeled inner left side and outer right side to signify something like an “inner” section.
Here’s the code I have so far:
library(tidyr)
library(ggplot2)
library(grid) # For arrow customization
# Define the vectors
st <- c("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10")
y1 <- c(5, 1, 4, 6, 2, 3, 7, 8, 2, 8) # Create more example data
y2 <- c(3, 3, 3, 3, 4, 4, 5, 5, 7, 7)
# Create a data frame
df <- data.frame(st = st, y1 = y1, y2 = y2)
# Pivot from wide to long
df_long <- df %>%
pivot_longer(
cols = c("y1", "y2"), # Columns to pivot
names_to = "variable", # Column name for variable names
values_to = "value" # Column name for values
)
# Create the plot
ggplot(data = df_long, aes(x = st, y = value, color = variable, group = variable)) +
geom_line(size = 1.2) + # Adjust line thickness
labs(
title = "Line Plot with Arrow Beneath X-Axis",
x = "Identifier",
y = "Value",
color = "Variable"
) +
theme_minimal() + # Use a clean theme for better visualization
geom_segment(
aes(x = 1, y = -1, xend = 10, yend = -1), # Line for "inner" section
arrow = arrow(type = "closed", length = unit(0.2, "inches")),
color = "blue",
size = 1.2
) +
annotate("text", x = 3, y = -1.5, label = "Inner", color = "blue", size = 4) + # Label for inner
annotate("text", x = 8, y = -1.5, label = "Outer", color = "red", size = 4) # Label for outer
I tried this also
+ geom_line(size = 1.2) + # Adjust line thickness
geom_hline(yintercept = 0, linetype = "dashed") + # Add horizontal line at y = 0
geom_vline(xintercept = -1, linetype = "dashed") + # Add vertical line at x = 0
but didnt get arrow line benethe the x axis outside the plot
Kindly correct my code, Thanks in advance