首页 > 解决方案 > 双geom_bar,如何获取每个条的值

问题描述

我有两个不同时间段(Y 轴)的国家(X 轴)的 ggplot,所以每个国家都有双条。我想看看每个酒吧的价值。我使用了 geom_text,但我在同一行得到了值,所以它们没有到位。我如何将 geom_text 用于这种类型的情节?

Rcountry %>%
  gather("Type", "Value",-Country) %>%
  ggplot(aes(Country, Value, fill = Type)) +
  geom_bar(position = "dodge", stat = "identity") + 
  coord_flip()+
  theme_minimal()+scale_fill_grey()+
  theme(legend.position="bottom")+
  theme(legend.title = element_blank())+
  scale_fill_manual(values=c("darkslategray4", "darkslategrey"))+
  labs(x="Country", y="Stock of robots per thousands worker in '000")+
  geom_text(aes(label=c(X2010, X2018)), size=3.5)```

Thank you

标签: ggplot2geom-bargeom-text

解决方案


这可以通过添加position = position_dodge(.9)to来实现geom_text,即您必须使用 in 的定位geom_bargeom_text获得正确的标签。使用mtcars示例数据,试试这个:

library(ggplot2)
library(dplyr)

mtcars2 <- mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(mpg = mean(mpg)) %>% 
  ungroup()

ggplot(mtcars2, aes(x = factor(cyl), mpg, fill = factor(gear))) + 
  geom_bar(position = "dodge", stat = "identity") +
  theme_minimal() + 
  scale_fill_grey() +
  theme(legend.position="bottom")+
  theme(legend.title = element_blank())+
  labs(x="Country", y="Stock of robots per thousands worker in '000")+
  geom_text(aes(label = mpg), position = position_dodge(.9), size=3.5) +
  coord_flip()

reprex 包(v0.3.0)于 2020-04-15 创建


推荐阅读