我正在使用 Covid 資料開展一個專案,我希望將來自三個國家的 Covid 資料繪制(然后比較):荷蘭、德國、法國都在同一個圖上。
我希望將 x 軸命名為“日期”,將 y 軸命名為“確診病例數”以及圖例的標題“國家 COVID 病例”。
到目前為止,我已經創建了一個包含所有三個縣的資料的最終資料框,稱為“dfFinal”。我包含的 ggplot不起作用(因為我不知道如何編碼)。我只是在繪制資訊時遇到了麻煩。有人可以幫忙嗎?資料已使用 Jsonlite 進行讀取收集,無需資料集即可輕松重新創建。
結構(串列(國家= c(“荷蘭”,“荷蘭”,“荷蘭”,“荷蘭”,“荷蘭”,“荷蘭”,“荷蘭”,“荷蘭”,“荷蘭”,“荷蘭”,“荷蘭", "荷蘭", "荷蘭", "荷蘭", "荷蘭"), 日期 = 結構 (c(18317, 18318, 18319, 18320, 18321, 18322, 18323, 18324, 18325, 18326, 18327, 18328, 18329 , 18330, 18331), class = "Date"), Cases = c(0L, 1L, 6L, 10L, 18L, 24L, 38L, 82L, 128L, 188L, 265L, 321L, 382L, 503L, 603L)), 行.names = 36:50, class = "data.frame")
install.packages("jsonlite", dependencies = TRUE)
library("jsonlite")
tmp <- readLines("https://pomber.github.io/covid19/timeseries.json")
jsonLot <- fromJSON(tmp)
myjsonLot <- toJSON(jsonLot, pretty=TRUE)
fileConn <- file(paste0("Covid19_timeseries.json"))
writeLines(myjsonLot, fileConn)
dfN <- data.frame(Country = c("Netherlands"), Date = c(jsonLot$Netherlands$date), Cases =
c(jsonLot$Netherlands$confirmed))
dfN[,]
dfG <- data.frame(Country = c("Germany"), Date = c(jsonLot$Germany$date), Cases =
c(jsonLot$Germany$confirmed))
dfG[,]
dfF <- data.frame(Country = c("France"), Date = c(jsonLot$France$date), Cases =
c(jsonLot$France$confirmed))
dfF[,]
dfFinal <- rbind.fill(dfN, dfG, dfF)
View(dfFinal)
ggplot(dfFinal, aes(x=Date, y=Cases) geom_line(size=1)
xlab("Date") ylab("Number of confirmed cases") scale_x_datetime(breaks = "1 day")
geom_line(aes(y=dfN$Cases), colour ="red")
geom_line(aes(y=dfG$Cases), colour ="red")
geom_line(aes(y=dfF$Cases), colour ="red"))
uj5u.com熱心網友回復:
您的代碼不起作用,因為您應該將其他呼叫添加geom_line()到外部,而不是內部xlab()。ggplot()我修好了它:
dfFinal$Date <- as.POSIXct(dfFinal$Date)
ggplot(dfFinal, aes(x=Date, y=Cases, group=Country))
geom_line(size=1)
xlab("Date")
ylab("Number of confirmed cases")
scale_x_datetime(breaks = "1 day")
我還添加了Date變數的轉換,因為當您讀取 JSON 時,它的格式不正確。
但是,您的代碼風格不是很好。我以更符合 tidy R 代碼標準的方式重新創建了其余的資料轉換。
library(jsonlite)
library(dplyr) # for data transformation and piping
library(purrr) # for mapping and binding
library(ggplot2)
# combine function calls by piping them, see help for `%>%` for details
dat <- readLines("~/../Desktop/timeseries.json") %>% fromJSON()
# for each of the data frames in the json append the name of the data.frame as
# "Country" variable and then bind all of them
dat <- imap_dfr(dat, ~ .x, .id = "Country") %>%
mutate(Date = as.POSIXct(date)) %>% # transform date into a proper format
filter(Country %in% c("Netherlands", "France", "Germany")) # filter data by focus countries
ggplot(dat, aes(x = Date, y = confirmed, group = Country, color = Country))
geom_line(size=1)
ggtitle("Number of COVID-19 casses in selected countries")
xlab("Date")
ylab("Number of confirmed cases")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/466709.html
下一篇:重新創建沒有資料的繪圖
