【问题标题】:The labels are below the bars in the R barplot标签位于 R 条形图中的条形下方
【发布时间】:2019-12-04 20:48:40
【问题描述】:

我试图将标签放在情节上的所有条上,但其中一些一直在条下。我应该在代码中编辑什么?

ggplot(data, aes(x = year,y = value)) + 
  geom_text(aes(label=value),  vjust=-3.5, size=3.5)+
  geom_bar(aes(fill = variable), stat = "identity",position = "dodge")+
  scale_x_continuous(breaks = unique(data$year))+
  ylab("Number of candidates")+
  theme(axis.title.x=element_blank())+
  scale_fill_discrete(name="",
                      labels=c("All", "Female"))

【问题讨论】:

  • 图层按照您提供的顺序绘制。您在文本层之后绘制了一个条形层

标签: r ggplot2 label bar-chart


【解决方案1】:

您需要将position_dodge 添加到您的geom_text 以跟随geom_bar 的position_dodge。

在这里,我以使用pivot_longer 重塑的iris 数据集为例

library(tidyverse)
ir_df <- iris %>% group_by(Species) %>% 
  summarise(Mean_Length = mean(Sepal.Length), Mean_Width = mean(Sepal.Width)) %>% 
  pivot_longer(., -Species, names_to = "Variables", values_to = "Value")

library(ggplot2)
ggplot(ir_df, aes(x = Species, y = Value, fill = Variables))+
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_text(aes(label = Value), vjust = -3.5, position = position_dodge(width = 1))

如果您未能成功将此代码适应您的数据集,请考虑提供您的数据集的reproducible example

【讨论】:

    猜你喜欢
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 2022-01-23
    • 1970-01-01
    • 2022-10-03
    • 2011-04-07
    • 1970-01-01
    相关资源
    最近更新 更多