gpt4 book ai didi

r - 如何在ggplot2中将标签居中放置在并排条形图上

转载 作者:行者123 更新时间:2023-12-01 23:09:27 25 4
gpt4 key购买 nike

我在 ggplot 工作。我创建了一个条形图,但条形图上的标签并未居中(见图)。

如何在此图中将每个条形图的标签置于其各自条形图的中心?

enter image description here

代码如下:

df<- structure(list(Cycle = c(1980, 1982, 1984, 1986, 1988, 1990, 
1992, 1994, 1996, 1998, 2000, 2002, 2004, 2006, 2008, 2010, 2012,
2014, 2016, 1980, 1982, 1984, 1986, 1988, 1990, 1992, 1994, 1996,
1998, 2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016),
Donor_Location = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L), .Label = c("In District", "Out of District"), class = "factor"),
Count_Percentage_Mean = c(0.167598290871218, 0.124829496296588,
0.0940731004562636, 0.125521769946444, 0.134545184854301,
0.221904402021545, 0.241031685849158, 0.284978425863672,
0.280387277343076, 0.269095218446438, 0.273131304975636,
0.288912758780087, 0.297134465175358, 0.296786491472909,
0.292365465524159, 0.303877491711499, 0.249983664094922,
0.258636305966848, 0.239182241578899, 0.159250631842859,
0.161311478778858, 0.157209833306125, 0.161853462566676,
0.174277618030726, 0.251786815739142, 0.318324841334214,
0.312697665544327, 0.347430615609066, 0.346833684171301,
0.374139881841685, 0.422610276126137, 0.432433986875512,
0.424992976111316, 0.429557833404775, 0.443001597806887,
0.462424440669885, 0.45460402775165, 0.492540191333363)), row.names = c(NA,
-38L), class = "data.frame")


ggplot(df, aes(x = Cycle , y = Count_Percentage_Mean, fill = Donor_Location)) +
geom_bar(stat = "identity", position = 'dodge') +
scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
geom_text(aes(label=paste(round(Count_Percentage_Mean*100,0), "%", sep = "")), position=position_dodge(width=0.9), vjust=-0.5)

谢谢!

最佳答案

嗯。不幸的是,我不能告诉你这个问题的原因是什么。此外,我不知道 ggplot2 的任何更新或......可能我错过了一些基本的东西(也许我需要另一杯咖啡)。反正。我查看了 layer_data,您的文本标签只是被条形宽度的一半所遮挡。因此,您可以通过将宽度加倍来实现您想要的结果,即在 geom_text

中使用 position = position_dodge(width = 1.8)
library(ggplot2)

ggplot(df, aes(x = Cycle, y = Count_Percentage_Mean, fill = Donor_Location)) +
geom_col(position = "dodge") +
scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
geom_text(aes(label = scales::percent(Count_Percentage_Mean, accuracy = 1)), position = position_dodge(width = 1.8), vjust = -0.5)

关于r - 如何在ggplot2中将标签居中放置在并排条形图上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70196479/

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