将标签对齐到ggplot中的boxplot

问题描述 投票:1回答:1

我有多个箱图,我希望用上面的实际值标注。但是,我似乎无法使它们对齐。我最终得到了以下标签未对齐的内容。

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
r ggplot2 label
1个回答
3
投票

干杯,将fill=variable从你的geom bar更改为你的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

© www.soinside.com 2019 - 2024. All rights reserved.