r - 如何在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)
解决方案
要添加标签,只需将变量与标签上的值映射(从您的屏幕截图中我猜您想添加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 创建
推荐阅读
- java - 通过java挂起运行可执行文件
- python - 使用自定义视频编写器库编写音频的错误
- angular - 获取不同组件上的活动选项卡 - 离子
- java - 在 Selenium 中处理 PopU
- java - 从哈希图中删除键
- java - 我怎样才能使它使用多个线程作为客户端-它们都在 switch 语句中执行一个任务
- excel - 使用 Excel VBA 自动化 IE:无需在站点中输入内容
- mvvm - 如何检测listview xamarin表单中的可点击标签位置
- javascript - js中的var char不起作用
- laravel - 如何检查表单输入是否有文件 laravel?