gpt4 book ai didi

r - 如何防止两个标签在条形图中重叠?

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

下图显示了使用以下代码创建的图表。我突出显示了丢失或重叠的标签。有没有办法告诉ggplot2不重叠标签?

week = c(0, 1, 1, 1, 1, 2, 2, 3, 4, 5)
statuses = c('Shipped', 'Shipped', 'Shipped', 'Shipped', 'Not-Shipped', 'Shipped', 'Shipped', 'Shipped', 'Not-Shipped', 'Shipped')

dat <- data.frame(Week = week, Status = statuses)

p <- qplot(factor(Week), data = dat, geom = "bar", fill = factor(Status))
p <- p + geom_bar()
# Below is the most important line, that's the one which displays the value
p <- p + stat_bin(aes(label = ..count..), geom = "text", vjust = -1, size = 3)
p

最佳答案

您可以使用著名的population pyramid的变体。

一些样本数据(受Didzis Elferts的回答启发的代码):

set.seed(654)
week <- sample(0:9, 3000, rep=TRUE, prob = rchisq(10, df = 3))
status <- factor(rbinom(3000, 1, 0.15), labels = c("Shipped", "Not-Shipped"))
data.df <- data.frame(Week = week, Status = status)

计算每周的计数分数,然后将一个类别转换为负值:
library("plyr")
plot.df <- ddply(data.df, .(Week, Status), nrow)
plot.df$V1 <- ifelse(plot.df$Status == "Shipped",
plot.df$V1, -plot.df$V1)

画图。请注意,y轴标签适用于在基线的任一侧显示正值。
library("ggplot2")
ggplot(plot.df) +
aes(x = as.factor(Week), y = V1, fill = Status) +
geom_bar(stat = "identity", position = "identity") +
scale_y_continuous(breaks = 100 * -1:5,
labels = 100 * c(1, 0:5)) +
geom_text(aes(y = sign(V1) * max(V1) / 30, label = abs(V1)))

剧情:

出于生产目的,您需要动态确定适当的y轴刻度标签。

关于r - 如何防止两个标签在条形图中重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16127170/

25 4 0