我有疾病和天数的数据。我必须为每种疾病及其感染的天数绘制一张柱状图。我用ggplot2试过了。然而,它结合了l不想要的相同疾病的日期。我有兴趣画出每一天的每一列,而不考虑疾病类型。我用了下面的代码。
original_datafile <-
structure(list(disease = structure(c(1L, 2L,
3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 6L, 6L, 6L),
.Label = c("AA", "BB", "CC", "DD", "EE", "FF"),
class = "factor"), days = c(5L, 5L, 9L, 2L,
3L, 4L, 4L, 5L, 7L, 15L, 3L, 7L, 7L, 15L)),
class = "data.frame", row.names = c(NA, -14L))
library(ggplot2)
ggplot(data = original_datafile, aes(x = disease, y = days)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 40, hjust = 1))
任何建议都将不胜感激。
发布于 2019-01-25 04:16:39
这里有几个我想出来的解决方案。不是100%确定这是否是你想要的,但希望这能让你更接近。为了为每个单独的行创建一个条形图,而不是将它们组合在一起,我创建了一个名为id
的新列,它只是作为每种疾病的每行的计数器。然后,我加入了两种可能的ggplot组合,我相信这两种组合更接近你想要的。
original_datafile <-
structure(list(disease = structure(c(1L, 2L,
3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 6L, 6L, 6L),
.Label = c("AA", "BB", "CC", "DD", "EE", "FF"),
class = "factor"), days = c(5L, 5L, 9L, 2L,
3L, 4L, 4L, 5L, 7L, 15L, 3L, 7L, 7L, 15L)),
class = "data.frame", row.names = c(NA, -14L))
library(ggplot2)
# Modified data file adds an 'id' column to split each row individually.
modified_datafile <- original_datafile %>%
group_by(disease) %>%
mutate(id = row_number())
# Facetted ggplot - each disease has its own block
ggplot(data = modified_datafile, aes(x = id, y = days)) +
geom_bar(stat = 'identity', position = 'dodge') +
theme(axis.text.x = element_text(angle = 40, hjust = 1)) +
facet_wrap(. ~ disease, nrow = 2) +
theme(axis.text.x = element_blank()) +
labs(x = '', y = 'Days')
# Non facetted ggplot - closer to original, but each row has a bar.
ggplot(data = modified_datafile, aes(x = disease, y = days, group = id)) +
geom_bar(stat = 'identity', position = position_dodge2(preserve = 'single')) +
theme(axis.text.x = element_text(angle = 40, hjust = 1))
https://stackoverflow.com/questions/54306053
复制相似问题