首页 > 解决方案 > 如何使用 ggplot2 修复 geom_text 的位置

问题描述

我想做一个这样的图表。

在此处输入图像描述

但我得到了类似的东西。

在此处输入图像描述

这是我的数据框。

 dput(mydata4)
structure(list(원격.수업.방식 = c("A", "A", "A/B", "A/B", "A/B/C", 
"A/B/C", "A/C", "A/C", "B", "B", "B/C", "B/C", "C", "C"), name = c("학업.기여도.x", 
"학업.기여도.y", "학업.기여도.x", "학업.기여도.y", "학업.기여도.x", 
"학업.기여도.y", "학업.기여도.x", "학업.기여도.y", "학업.기여도.x", 
"학업.기여도.y", "학업.기여도.x", "학업.기여도.y", "학업.기여도.x", 
"학업.기여도.y"), value = c(1.955, 1.121, 2.25, 1.035, 2.5, 1.179, 
3, 1.414, 2.718, 1.324, 2.75, 0.957, 2.727, 1.302)), row.names = c(NA, 
-14L), class = c("tbl_df", "tbl", "data.frame"))

这是我使用的代码。

library(ggplot2) 
library(tidyverse)

mydata4 <- mydata4 %>% pivot_longer(cols = c(학업.기여도.x, 학업.기여도.y), names_to = 'name', values_to = 'value')

mydata4
# A tibble: 14 x 3

ggplot(data=mydata4) + geom_col(aes(x=원격.수업.방식, y = value, fill=name), position="dodge") + ggtitle("원격 수업 방식 별 학업기여도(평균/표준편차)") +theme(plot.title = element_text( face = "bold", hjust = 0.5, size = 20, color = "black")) + geom_text(aes(x=원격.수업.방식, y=value ,label=value) , position = position_dodge(.9))

当我使用这个时,

   geom_text(aes(x=원격.수업.방식, y=value ,label=value) , position = position_dodge(.9), vjust=0.2, hjust=0.2)

[ 在此处输入图像描述 3

标签: rggplot2

解决方案


我无法重现该示例,而是查看您的代码和绘图。我想你所需要的只是在垂直和水平方向上做一个小的调整。只需添加两个参数geom_text(请参阅下文)

geom_text(aes(x=원격.수업.방식, y=value ,label=value) , position = position_dodge(.9), vjust=-0.25)

我不确定结果。如果它的出现不同,您可以vjust通过hjust更改geom_text. 它基本上沿垂直和水平轴移动文本。

(已编辑)在下面尝试

  attach(mydata4)
  ggplot(mydata4) + 
  aes(x=원격.수업.방식, y = value, fill=name) + 
  geom_bar(position = 'dodge', stat='identity') + 
  ggtitle("원격 수업 방식 별 학업기여도(평균/표준편차)") +
  theme(plot.title = element_text( face = "bold", hjust = 0.5, size = 20, color = "black")) + 
  geom_text(aes(label=value), position=position_dodge(0.9), vjust=-0.25)

推荐阅读