gpt4 book ai didi

r - 条形图上的 geom_text 位置中间

转载 作者:行者123 更新时间:2023-12-03 22:50:24 25 4
gpt4 key购买 nike

需要帮助对齐条形图上的标签。

这是可重现的代码:

library(ggmap)
library(ggplot2)
library(gganimate)
library(readxl)
library(animation)

mydf1<-structure(list(year = c(1994, 1995, 1997, 1997, 1998, 1998, 2000,
2000, 2001, 2001, 2002, 2002, 2004, 2005, 2005, 2006, 2006, 2007,
2007, 2008, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2015,
2016, 2016, 2016, 2016), N = c(3L, 1L, 1L, 4L, 1L, 4L, 1L, 2L,
1L, 5L, 1L, 2L, 1L, 1L, 4L, 1L, 3L, 1L, 2L, 1L, 5L, 2L, 2L, 6L,
4L, 1L, 1L, 2L, 1L, 1L, 3L, 4L, 1L), channels = c(86, 24, 24,
68, 6, 34, 22, 10, 14, 24, 16, 43, 4, 20, 56, 15, 20, 8, 11,
24, 44, 9, 23, 65, 20, 12, 5, 43, 5, 4, 24, 53, 14),
reliability = c(0.466666666666667,
1, 0.2, 0.8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), type = c("OIL", "LNG",
"AGS", "OIL", "LNG", "OIL", "LNG", "OIL", "LNG", "OIL", "LNG",
"OIL", "OIL", "LNG", "OIL", "LNG", "OIL", "LNG", "OIL", "LNG",
"OIL", "OIL", "OIL", "OIL", "OIL", "OIL", "LNG", "LNG", "OIL",
"AGS", "LNG", "LNG*", "OIL")), .Names = c("year", "N",
"channels", "reliability", "type"), row.names = c(NA, -33L), class = "data.frame")

p3<-ggplot(data=mydf1, aes(x=year, y=channels, frame=year, cumulative=TRUE, fill=type))+
geom_bar(stat="identity")+labs(x="year", y="y")+
geom_text(aes(label=channels), vjust=1, color="white", size=3)+theme_minimal()+
ggtitle("Data here", "statistics")
p3

问题在于标签的位置 - 它们与相应的条形不匹配。请参阅图片以获取解释。

enter image description here

如何在对应栏的中间添加标签?

最佳答案

随着最近更新 ggplot2 ,您可以通过设置 position = position_stack(vjust = 0.5) 来做到这一点。在 geom_text() .

您可能也感兴趣,您可以使用 geom_col()作为 geom_bar(stat = "identity") 的快捷方式.另外,labs有标题和副标题参数,所以你不需要使用它和ggtitle .

ggplot(data = mydf1, aes(x = year, y = channels, fill = type, frame = year, cumulative = TRUE)) +
geom_col() +
labs(x = "year", y = "y", title = "Data Here", subtitle = "Statistics") +
geom_text(aes(label = channels), color = "white", size = 3, position = position_stack(vjust = 0.5)) +
theme_minimal()

enter image description here

关于r - 条形图上的 geom_text 位置中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41877645/

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