簡體   English   中英

使用ggplot的R barplot

[英]R barplot using ggplot

我有疾病和天數的數據。 我必須為每種疾病及其感染天數繪制一個地勢圖。 我嘗試使用 但是,它結合了我不想要的相同疾病的天數。 我有興趣每天繪制每列而不管疾病類型如何。 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))

任何建議,將不勝感激。

這是我工作的幾個解決方案。 不能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))

在此處輸入圖片說明

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM