Ответ 1
Я вижу, что @Brandon Bertelsen опубликовал отличный ответ. Я хотел бы добавить код, в котором рассматриваются дополнительные сведения, упомянутые в исходном сообщении:
- После того, как вы измените свои данные и присвоите статус здоровья
fill
, ggplot автоматически создаст легенду. - Я предлагаю использовать
scale_fill_manual()
для получения точных граней, упомянутых в исходном сообщении. -
theme_bw()
- удобная функция, позволяющая быстро получить черно-белый вид вашего сюжета. - Порядок построения коэффициентов уровней/цветов можно контролировать, указав желаемый порядок с аргументом
levels
factor()
. - Уклоненный барплот (вместо штабелирования) может иметь некоторые преимущества для этого набора данных.
library(reshape2)
library(ggplot2)
x <- as.data.frame(list(variable=c("QUAG", "QUKE", "QUCH"),
alive=c(627, 208, 109), infected=c(102, 27, 0),
dead=c(133, 112, 12), sod.dead=c(49, 8, 0)))
# Put data into 'long form' with melt from the reshape2 package.
dat = melt(x, id.var="variable", variable.name="status")
head(dat)
# variable status value
# 1 QUAG alive 627
# 2 QUKE alive 208
# 3 QUCH alive 109
# 4 QUAG infected 102
# 5 QUKE infected 27
# 6 QUCH infected 0
# By manually specifying the levels in the factor, you can control
# the stacking order of the associated fill colors.
dat$status = factor(as.character(dat$status),
levels=c("sod.dead", "dead", "infected", "alive"))
# Create a named character vector that relates factor levels to colors.
grays = c(alive="gray85", dead="gray65", infected="gray38", sod.dead="black")
plot_1 = ggplot(dat, aes(x=variable, y=value, fill=status)) +
theme_bw() +
geom_bar(position="stack") +
scale_fill_manual(values=grays)
ggsave(plot=plot_1, filename="plot_1.png", height=5, width=5)
# You may also want to try a dodged barplot.
plot_2 = ggplot(dat, aes(x=variable, y=value, fill=status)) +
theme_bw() +
geom_bar(position="dodge") +
scale_fill_manual(values=grays)
ggsave(plot=plot_2, filename="plot_2.png", height=4, width=5)