簡體   English   中英

Y 軸值與 R 中數據集中的實際列不同

[英]Y axis values different from actual column in dataset in R

我目前正在處理“世界銀行群島”的數據集。 在那,我正在嘗試 plot 每年的人口與國家圖表。 下面是我完成的代碼。

library(ggplot2)
options(scipen = 999)
bank <- read.csv("C:/Users/True Gamer/OneDrive/Desktop/world_bank_international_arrivals_islands.csv")
bank[bank == "" | bank == "."] <- NA
bank$country <- as.numeric(bank$country)
bank$year <- as.numeric(bank$year)
bank$areakm2 <- as.numeric(bank$areakm2)
bank$pop <- as.numeric(bank$pop)
bank$gdpnom <- as.numeric(bank$gdpnom)
bank$flights...WB <- as.numeric(bank$flights...WB)
bank$hotels <- as.numeric(bank$hotels)
bank$hotrooms <- as.numeric(bank$hotrooms)
bank$receipt <- as.numeric(bank$receipt)
bank$ovnarriv <- as.numeric(bank$ovnarriv)
bank$dayvisit <- as.numeric(bank$dayvisit)
bank$arram <- as.numeric(bank$arram)
bank$arreur <- as.numeric(bank$arreur)
bank$arraus <- as.numeric(bank$arraus)
str(bank)
plot1 <- ggplot(bank, aes(x=country,y=pop)) + geom_bar(stat = "identity",aes(fill=year))  + ggtitle("Population of each country yearwise") + xlab("Countries") + ylab("Population")
plot1

但是,當我這樣做時,圖表上顯示的 y 值與實際 y 值不同。 這是數據集的鏈接

問題是您正在堆疊條形圖(這是默認行為)。 此外, geom_bar(stat = "identity")只是編寫geom_col的很長的路要走。 需要注意的另一點是,由於所有列都是數字,所以單行:

bank <- as.data.frame(lapply(bank, as.numeric))

替換您所有的個人數字轉換。

您嘗試創建的 plot 應該是這樣的:

 ggplot(bank, aes(x = country, y = pop)) + 
   geom_col(aes(fill = factor(year)), position = "dodge")  + 
   ggtitle("Population of each country yearwise") + 
   xlab("Countries") + 
   ylab("Population") +
   labs(fill = "Year") +
   scale_y_continuous(labels = scales::comma) +
   scale_x_continuous(breaks = 1:27)

在此處輸入圖像描述

但是,最好以不同的方式呈現您的數據。 也許,如果你比較人口增長,這樣的事情會更好:

 ggplot(bank, aes(x = year, y = pop)) + 
   geom_line(aes(color = factor(country)), position = "dodge")  + 
   ggtitle("Population of each country yearwise") + 
   xlab("Year") + 
   ylab("Population") +
   facet_wrap(.~country, scales = "free_y", nrow = 6) +
   scale_y_continuous(labels = scales::comma) +
   scale_x_continuous(breaks = c(0, 5, 10)) +
   theme_minimal() +
   theme(legend.position = "none")

在此處輸入圖像描述

或帶酒吧:

 ggplot(bank, aes(x = year, y = pop)) + 
   geom_col(aes(fill = factor(country)), position = "dodge")  + 
   ggtitle("Population of each country yearwise") + 
   xlab("Year") + 
   ylab("Population") +
   facet_wrap(.~country, scales = "free_y", nrow = 6) +
   scale_y_continuous(labels = scales::comma) +
   scale_x_continuous(breaks = c(0, 5, 10)) +
   theme_minimal() +
   theme(legend.position = "none")

在此處輸入圖像描述

暫無
暫無

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

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