问题: 我正在尝试在 ggplot2 中创建一个绘图,其中箭头线指向外部,并位于 x 轴下方。我在 ggplot2 中使用了 geom_segment 函数,但它在绘图上绘制。我想要这条线有一个指向右侧的箭头,位于 x 轴下方,标记为左侧内侧和右侧外侧,以表示类似“内部”部分的内容。
这是我到目前为止的代码:
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
我也尝试过这个
+ 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
但没有在图外的 x 轴下方得到箭头线
请更正我的代码,提前致谢
根据您的代码,一个快速选项是通过
coord_cartesian
设置限制,以便箭头绘制在面板之外。另外设置 clip="off"
并通过增加例如为箭头留出一些空间。绘图的下边距:
library(ggplot2)
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.5, xend = 10, yend = -1.5), # Line for "inner" section
arrow = arrow(type = "closed", length = unit(0.2, "inches")),
color = "blue",
size = 1.2
) +
annotate("text", x = 3, y = -2, label = "Inner", color = "blue", size = 4) + # Label for inner
annotate("text", x = 8, y = -2, label = "Outer", color = "red", size = 4) +
coord_cartesian(clip = "off", ylim = c(0, NA)) +
theme(plot.margin = margin(5.5, 5.5, 50, 5.5))