gpt4 book ai didi

r - ggplot2 中堆叠框的直方图

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

我目前正在尝试制作的图表略微落在两个凳子之间。我想制作一个由堆叠和标记的框组成的直方图。这是我正在谈论的事情的一个例子,摘自纽约时报最近的一篇文章:

http://farm8.staticflickr.com/7109/7026409819_1d2aaacd0a.jpg

是否可以使用 ggplot2 实现此目的?

为了稍微放大这个问题,到目前为止我所拥有的是:

dfr <- data.frame(
name = LETTERS[1:26],
percent = rnorm(26, mean=15)
)

ggplot(dfr, aes(x=percent, fill=name)) + geom_bar() +
stat_bin(geom="text", aes(label=name))

...我显然做错了。最终,我最理想的是沿着下面手动修改的图表的线条,(比如说)字母 A 到 M 填充一个阴影,N 到 Z 填充另一个阴影。

http://farm8.staticflickr.com/7116/7026536711_4df9a1aa12.jpg

最佳答案

给你!

set.seed(3421)
# added type to mimick which candidate is supported
dfr <- data.frame(
name = LETTERS[1:26],
percent = rnorm(26, mean=15),
type = sample(c("A", "B"), 26, replace = TRUE)
)

# easier to prepare data in advance. uses two ideas
# 1. calculate histogram bins (quite flexible)
# 2. calculate frequencies and label positions
dfr <- transform(dfr, perc_bin = cut(percent, 5))
dfr <- ddply(dfr, .(perc_bin), mutate,
freq = length(name), pos = cumsum(freq) - 0.5*freq)

# start plotting. key steps are
# 1. plot bars, filled by type and grouped by name
# 2. plot labels using name at position pos
# 3. get rid of grid, border, background, y axis text and lables
ggplot(dfr, aes(x = perc_bin)) +
geom_bar(aes(y = freq, group = name, fill = type), colour = 'gray',
show_guide = F) +
geom_text(aes(y = pos, label = name), colour = 'white') +
scale_fill_manual(values = c('red', 'orange')) +
theme_bw() + xlab("") + ylab("") +
opts(panel.grid.major = theme_blank(), panel.grid.minor = theme_blank(),
axis.ticks = theme_blank(), panel.border = theme_blank(),
axis.text.y = theme_blank())

enter image description here

关于r - ggplot2 中堆叠框的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9924214/

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