我用点和一条水平线画了一个图。下面是示例代码:
dt <- data.frame(ID = c("Line",
"P1",
"P2",
"P3"),
Year = "2016",
Value = c(1, 0.533, 1.233, 0.233))
dt$Value <- format(dt$Value, digits = 2)
library(ggplot2)
# Unexpected horizontal line
ggplot(NULL) +
geom_point(data = subset(dt, ID != "Line"),
aes(x = Year, y = Value, color = ID, shape = ID)) +
geom_text(data = subset(dt, ID != "Line"),
aes(label = subset(dt, ID != "Line")$Value,
x = Year, y = Value)) +
geom_hline(yintercept = as.numeric(subset(dt, ID == "Line")$Value),
color = "red") +
theme_bw()
然而,下面的图看起来很奇怪:红色的水平线在y轴上是0.23,而不是1。为什么会发生这种情况?谢谢!
1条答案
按热度按时间vlju58qv1#
因为
format
会将Value
转换为字符类型,因此ggplot
不再将其识别为连续类型。您需要使用数字y轴绘制图形,然后根据需要的格式处理文本标签和y轴分隔符(注意,我创建了一个Value2
列来存储格式化字符Value
)。创建于2023-05-26带有reprex v2.0.2