首页 > 解决方案 > 将 geom_text 接地到 x 轴(例如 y =0)

问题描述

我有一个用 ggplot 制作的图表,如下所示:

泡泡糖

我希望将每个条上的数字标签接地/粘合到 y <= 0 的 x 轴。

这是生成图形的代码:

ggplot(data=df) +
  geom_bar(aes(x=row, y=numofpics, fill = crop, group = 1), stat='identity') +
  geom_point(data=df, aes(x = df$row, y=df$numofparcels*50, group = 2), alpha = 0.25) +
  geom_line(data=df, aes(x = df$row, y=df$numofparcels*50, group = 2), alpha = 0.25) +
  geom_text(aes(x=row, y=numofpics, label=bbch)) +
  geom_hline(yintercept=300, linetype="dashed", color = "red", size=1) +
  scale_y_continuous(sec.axis= sec_axis(~./50, name="Number of Parcels")) +
  scale_x_discrete(name = c(),breaks = unique(df$crop), labels = as.character(unique(df$crop)))+
  labs(x=c(), y="Number of Pictures")

我已经尝试过vjustposition_nudge元素geom_text,但我能找到的每个解决方案都会将geom_text相应元素的每个元素的位置更改为其当前位置。因此,我尝试的一切都会导致这种情况:

泡泡糖2

如何使 ggplot 将文本接地到 y <= 0 的 x 轴底部,可能还可以引入 a angle = 45

链接到数据框 = https://drive.google.com/file/d/1b-5AfBECap3TZjlpLhl1m3v74Lept2em/view?usp=sharing

标签: rggplot2positiongeom-text

解决方案


我在阻止与谷歌驱动器的连接的代理服务器后面,因此我无法访问您的数据。我无法对此进行测试,但我会在我的数据集中引入一个新的标签字段,如果 y<0,则将 y 设置为 0:

df <- df %>%
  mutate(labelField = if_else(numofpics<0, 0, numofpics)

然后我会在我的 geom_text 调用中使用这个标签字段:

geom_text(aes(x=row, y=labelField, label=bbch), angle = 45)

希望有帮助。


推荐阅读