我有很多樹木的疾病評分,其中有連續兩年的枯萎/感染百分比讀數。我可以在創建直方圖ggplot2中的r每一年,但我如何創建并排側條形圖顯示與范圍如0-10,10-20,20-30%,達方每年側讀數x 軸 100% 感染?
我創建了一個簡單的資料框,每年有兩個讀數:
diseaseyear1 <- c(20, 30, 40, 50, 30, 20, 60, 85, 45, 32, 20, 40)
diseaseyear2 <- c(30, 35, 42, 45, 25, 70, 65, 90, 40, 25, 35, 50)
totaldisease <- tibble(diseaseyear1, diseaseyear2)
totaldisease
#I can plot year 1
quartz(10, 5)
year1 <- ggplot(totaldisease)
aes(x=diseaseyear1)
geom_histogram(binwidth = 10)
labs(title = "Disease Year 1",
y = "count", x = "% of disease")
theme(text = element_text(size = 10, family = "GillSans"))
#I can also plot year 2
year1 <- ggplot(totaldisease)
aes(x=diseaseyear1)
geom_histogram(binwidth = 10)
labs(title = "Disease Year 1 & 2",
y = "count", x = "% of disease")
theme(text = element_text(size = 10, family = "GillSans"))
#but how can I combine these two histograms (or bar plots) as side by side bars in one chart?

uj5u.com熱心網友回復:
我們需要首先將我們的資料轉換為長格式。這樣,我們可以更好地繪制資料。
totaldisease %>%
tidyr::pivot_longer(names_to = "dis", values_to = "val",
cols = 1:ncol(.)) %>%
ggplot(aes(val, fill=dis))
geom_histogram(binwidth = 10)
labs(title = "Disease Year 1 & 2",
y = "count", x = "% of disease")
theme(text = element_text(size = 10, family = "GillSans"))
結果

如果你需要它躲開
totaldisease %>%
tidyr::pivot_longer(names_to = "dis", values_to = "val",
cols = 1:ncol(.)) %>%
ggplot(aes(val, fill=dis))
geom_histogram(binwidth = 10, position = "dodge")
labs(title = "Disease Year 1 & 2",
y = "count", x = "% of disease")
theme(text = element_text(size = 10, family = "GillSans"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/381230.html
上一篇:選擇變數(使用`varSelectInput`)和使用帶有Shiny的ggplot時出錯(錯誤:`arg`必須是一個符號)
