gpt4 book ai didi

r - 将 geom_text 放置在躲避条形图上

转载 作者:行者123 更新时间:2023-12-03 05:11:11 26 4
gpt4 key购买 nike

我试图让标题不言自明,但这里是 - 数据优先:

dtf <- structure(list(variable = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 
4L, 4L, 5L, 5L), .Label = c("vma", "vla", "ia", "fma", "fla"), class = "factor"),
ustanova = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L), .Label = c("srednja škola", "fakultet"), class = "factor"),
`(all)` = c(42.9542857142857, 38.7803203661327, 37.8996138996139,
33.7672811059908, 29.591439688716, 26.1890660592255, 27.9557692307692,
23.9426605504587, 33.2200772200772, 26.9493087557604)), .Names = c("variable",
"ustanova", "(all)"), row.names = c(NA, 10L), class = c("cast_df",
"data.frame"), idvars = c("variable", "ustanova"), rdimnames = list(
structure(list(variable = structure(c(1L, 1L, 2L, 2L, 3L,
3L, 4L, 4L, 5L, 5L), .Label = c("vma", "vla", "ia", "fma",
"fla"), class = "factor"), ustanova = structure(c(1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("srednja škola",
"fakultet"), class = "factor")), .Names = c("variable", "ustanova"
), row.names = c("vma_srednja škola", "vma_fakultet", "vla_srednja škola",
"vla_fakultet", "ia_srednja škola", "ia_fakultet", "fma_srednja škola",
"fma_fakultet", "fla_srednja škola", "fla_fakultet"), class = "data.frame"),
structure(list(value = structure(1L, .Label = "(all)", class = "factor")), .Names = "value", row.names = "(all)", class = "data.frame")))

我想创建一个闪避条形图,执行coord_flip并在条形内放置一些文本标签:

ggplot(bar) + geom_bar(aes(variable, `(all)`, fill = ustanova), position = "dodge") +
geom_text(aes(variable, `(all)`, label = sprintf("%2.1f", `(all)`)), position = "dodge") +
coord_flip()

你可以看到输出here .

enter image description here

我认为我要求的是一些微不足道的东西。我希望文本标签“跟随”堆叠的条形。标签正确放置在 y 轴上,但如何将它们正确放置在 x 轴上?

最佳答案

这是你想要的吗?

library(ggplot2)

ggplot(bar) +
geom_col(aes(variable, `(all)`, fill = ustanova), position = "dodge") +
geom_text(aes(variable, `(all)`, label = sprintf("%2.1f", `(all)`), group = ustanova),
position = position_dodge(width = .9)) +
coord_flip()

关键是position = position_dodge(width = .9) (其中 .9 是条形的默认宽度)而不是 position = "dodge" ,这只是一个没有任何参数的快捷方式。此外,您还必须设置 group=ustanova美学geom_text躲避标签 ustanova (第二个选择是通过 fill = ustanova 使 ggplot(bar, aes(fill = ustanova)) 成为全局美学

<小时/>

ggplot2_2.0.0您可以在 ?geom_text 中找到几个示例关于如何定位geom_text在躲避或堆叠条上(名为“# Aligning labels and bars" 的代码块”)。问答 What is the width argument in position_dodge? 提供了对该主题的更全面的描述。

关于r - 将 geom_text 放置在躲避条形图上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6017460/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com