我目前试图制作的图表在两次大便之间有所下降。我想制作一个由堆叠和标记的框组成的直方图。以下是我正在谈论的事情的一个例子,取自纽约时报最近的一篇文章:
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
答案 0 :(得分:11)
你走了!
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())