首页 > 解决方案 > 如何在ggplot2中标记条形图

问题描述

我正在尝试制作一个非常简单的条形图(屏幕截图)。

我有两个问题:

首先,如何标记条形?我设法正确地标记了一个堆栈,但我不知道如何在不更改它们的情况下标记另一个堆栈。我想用 76 标记阴影并用 277 暴露?

其次,如何更改列的颜色,例如我想要红色和蓝色?

谢谢

my_data <-  read.csv("geum_data.csv")

graph <-ggplot(my_data, aes(exposure, seedling.count, fill = exposure)) + 
geom_col(width = 0.5) + theme(axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 0)))+
geom_text(aes(label= 76), position=position_dodge(width=0.9), vjust=-0.25) +
labs(fill = "Exposure")
graph <-  graph + labs(x = "Exposure", y = "Seedling Count avg.")
print (graph)

标签: rggplot2

解决方案


要添加标签,只需将变量与标签上的值映射(从您的屏幕截图中我猜您想添加seedling.count)。可以通过 更改颜色scale_fill_manual。尝试这个:

graph <- ggplot(my_data, aes(exposure, seedling.count, fill = exposure)) + 
  geom_col(width = 0.5) + 
  scale_fill_manual(values = c(Exposed = "red", Shaded = "blue")) +
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 0))) +
  geom_text(aes(label = seedling.count), position = position_dodge(width=0.9), vjust=-0.25) +
  labs(fill = "Exposure")

graph <- graph + labs(x = "Exposure", y = "Seedling Count avg.")
graph

使用mtcars示例数据,以下代码显示了这种方法的一个示例:

library(ggplot2)
library(dplyr)

mtcars %>% 
  group_by(cyl = factor(cyl)) %>% 
  summarise(mpg = mean(mpg)) %>% 
  ggplot(aes(cyl, mpg, fill = cyl)) +
  geom_col() +
  geom_text(aes(label = mpg), vjust=-0.25) +
  scale_fill_manual(values = c(`4` = "red", `6` = "blue", `8` = "green"))

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


推荐阅读