将标签与ggplot中的箱线图对齐

时间:2019-03-20 12:25:53

标签: r ggplot2 label

我有多个箱形图,希望用上面的实际值标记。但是,我似乎无法使它们对齐。我最终遇到类似于以下内容的标签未对齐的情况。

Boxplot 我尝试过修改

geom_text(aes(label=value), position=position_dodge(width=0.9), vjust=-1) 

但无济于事。任何建议将不胜感激。

我的脚本如下:

library(reshape2)
library(tidyverse)
library(dplyr)
library(ggplot2)
library(stringr)

barCount <- tibble::tribble(
  ~Year, ~Lateral.bar, ~Bar.accreted.to.island, ~Mid.channel.bar,
  1990,          105,                     134,               62,
  2010,          102,                     189,              102
)


df2 <- melt(barCount, id="Year") %>% 
  mutate(
    Year = Year %>% as.factor(),
    variable = variable %>% str_replace_all("\\.", " ")
  )

barPlot <- ggplot(df2, aes(Year,value)) +
  geom_bar(aes(fill=variable),position="dodge",stat="identity") +
  labs(y="Quantity",fill="")+
  scale_fill_manual("Legend",
                    values=c("Lateral bar"="khaki4", "Bar accreted to island"="Khaki2", 
                             "Mid channel bar"="honeydew4"))+
  geom_text(aes(label=value), position=position_dodge(width=0.9),vjust=-1) 


#modifying axis 
barPlot <- barPlot + theme(
  axis.title.x = element_blank(),
  axis.title.y = element_text(size=14),
  axis.text.x = element_text(size=14),
  legend.position="bottom" 

)

barPlot

1 个答案:

答案 0 :(得分:3)

欢呼,将fill=variable从地理栏更改为ggplot()调用(并通过hjust= .25调整水平:

barPlot <- ggplot(df2, aes(Year,value, fill= variable)) +
  geom_bar(position="dodge",stat="identity") +
  labs(y="Quantity",fill="")+
  scale_fill_manual("Legend",values=c("Lateral bar"="khaki4","Bar accreted to island"="Khaki2","Mid channel bar"="honeydew4"))+
  geom_text(aes(label=value),position=position_dodge(width=0.9),vjust=-1, hjust= .25) 

此结果: enter image description here