gpt4 book ai didi

r - 在堆积条形图上居中文本标签

转载 作者:行者123 更新时间:2023-12-04 12:19:24 24 4
gpt4 key购买 nike

条形图的颜色基于“MaskID”,在此代码中,我可以将“MaskID”名称制作为文本标签,但我希望名称以其相应的颜色为中心。

你会怎么做?

p <- ggplot(df, aes(x, y))
p <- p + xlab("xlabel")
p <- p + ylab("ylabel")
p <- p + ggtitle("ylabel vs xlabel")
p <- p + geom_bar(stat="identity", aes(fill=MaskID))
p <- p + theme(axis.text.x = element_text(angle=90, vjust=-0.005))
p <- p + geom_text(aes(label = ifelse(y != 0, as.character(MaskID), ''), angle=90))

(还要考虑文本标签不会显示为 0 y 值的条)
     MaskID        x     y
0 ABC Name1 0
1 ABC Name2 0
2 ABC Name3 1
3 ABC Name4 0
.. ... ... ...
100 DEF Name1 0
101 DEF Name2 0
102 DEF Name3 3
103 DEF Name4 4
104 DEF Name5 0

这是我正在构建的图表的一部分:

enter image description here

最佳答案

这似乎有效,尽管我认为这有点复杂。它使用 ggplot_build提取描述条形位置的数据,找到它们的中点和适当的标签,然后添加文本。

## Make the graph (-the text parts)
p <- ggplot(df, aes(x, y))
p <- p + xlab("xlabel")
p <- p + ylab("ylabel")
p <- p + ggtitle("ylabel vs xlabel")
p <- p + geom_bar(stat="identity", aes(fill=MaskID))
p <- p + theme(axis.text.x = element_text(angle=90, vjust=-0.005))

## Get the bar data from ggplot
dd <- ggplot_build(p)[[1]][[1]]

## Get the y-values in the middle of bars
xy <- unique(dd[dd$y != 0, c("x", "y")])
dat <- with(xy, data.frame(
x=x,
y=unlist(sapply(split(y, x), function(z) diff(c(0, z))/2 + head(c(0, z), -1)))
))

## Get the labels
labels <- with(df[df$y!=0,], unlist(split(MaskID, x)))

## Add the text using the new xy-values and labels
p + geom_text(data=dat, aes(x, y), label=labels, angle=90)

enter image description here

关于r - 在堆积条形图上居中文本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31665425/

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