R语言 ggplot2的意外水平线

dddzy1tm  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(145)

我用点和一条水平线画了一个图。下面是示例代码:

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。为什么会发生这种情况?谢谢!

vlju58qv

vlju58qv1#

因为format会将Value转换为字符类型,因此ggplot不再将其识别为连续类型。您需要使用数字y轴绘制图形,然后根据需要的格式处理文本标签和y轴分隔符(注意,我创建了一个Value2列来存储格式化字符Value)。

library(ggplot2)

dt <- data.frame(ID = c("Line",
                        "P1",
                        "P2",
                        "P3"),
                 Year = "2016",
                 Value = c(1, 0.533, 1.233, 0.233))

dt$Value2 <- format(dt$Value, digits = 2)

# 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 = Value2,
                x = Year, y = Value)) +
  geom_hline(yintercept = subset(dt, ID == "Line")$Value,
             color = "red") +
  scale_y_continuous(breaks = as.numeric(dt$Value2[dt$ID != "Line"])) +
  theme_bw()

创建于2023-05-26带有reprex v2.0.2

相关问题