r - R中的标签分组条形图
问题描述
我正在尝试将标签添加到 r 中的分组条形图。但是我在 y 轴上使用百分比,我希望标签是计数的。我尝试使用 geom_text() 函数,但我不知道我需要使用的参数有多精确。
newdf3 %>%
dplyr::count(key, value) %>%
dplyr::group_by(key) %>%
dplyr::mutate(p = n / sum(n)) %>%
ggplot() +
geom_bar(
mapping = aes(x = key, y = p, fill = value),
stat = "identity",
position = position_dodge()
) +
scale_y_continuous(labels = scales::percent_format(),limits=c(0,1))+
labs(x = "", y = "%",title="")+
scale_fill_manual(values = c('Before' = "deepskyblue", 'During' = "indianred1", 'After' = "green2", '?'= "mediumorchid3"),
drop = FALSE, name="")
这是我需要它的一个例子:
这是我正在使用的数据示例:
key value
A Before
A After
A During
B Before
B Before
C After
D During
...
我还想保留没有价值的酒吧(标签= 0)。
有人可以帮我弄这个吗?
解决方案
这是如何将计数标签添加到简单条形图的MWE 。有关将这些分组的情况,请参见下文。
library(datasets)
library(tidyverse)
data <- chickwts %>%
group_by(feed) %>%
count %>%
ungroup %>%
mutate(p = n / sum(n))
ggplot(data, aes(x = feed, y = p, fill = feed)) +
geom_bar(stat = "identity") +
geom_text(stat = "identity",
aes(label = n), vjust = -1)
你应该能够对你的数据做同样的事情。
编辑: StupidWolf 在评论中指出原始示例已分组数据。添加与此position = position_dodge(0.9)
的geom_text
交易。
同样,无法访问原始数据,但这里有一个不同的 MWE 使用mtcars
显示:
library(datasets)
library(tidyverse)
data <- mtcars %>%
as_tibble %>%
transmute(gear = as_factor(gear),
carb = as_factor(carb),
cyl = cyl) %>%
group_by(gear, carb) %>%
count
ggplot(data, aes(x = gear, y = n, fill = carb)) +
geom_bar(stat = "identity",
position = "dodge") +
geom_text(aes(label = n),
stat = "identity",
vjust = -1,
position = position_dodge(0.9))
推荐阅读
- python - 尝试在 model.fit() 中包含验证数据集时出现 Keras CNN 错误
- php - 获取 foreach 循环中的所有行并回显数组结果?
- python - 如何在Python中将两个图像连接在一起?
- javascript - TypeScript:从类型化函数中提取泛型类型
- amazon-web-services - Amazon Connect、Amazon Direct Connection、AWS Managed VPN 和 Amazon Connect 有什么区别
- linux - Android init.rc中mkdir参数的含义
- c++ - 使用依赖成员初始化程序进行聚合初始化,在 lambda 中实例化
- javascript - 在 Redux 中添加 Todo,无法读取属性 Symbol(Symbol.iterator)
- asp.net - 如何在 Razor 视图中将模型传递到另一个模型中?
- mongoose - 如何通过属性大小不达到特定数字或在 Mongoose 中为空或 null 的值获取对象