簡體   English   中英

在 R 和 ggplot2 的條形圖中排列條形時出現“na”問題

[英]Issue with “na” in arranging the bars in a bar plot in R and ggplot2

我正在嘗試使用 ggplot2 並在 R 中繪圖創建一個下降條形圖。我使用的數據是“a12”,它被 ggplot 在“#Final Data frame is used below”行下消耗。

如果您看到下面的快照,“a1”列中的“na”值應該位於圖中的第二個位置,但是它不遵循降序並被推到最后。

解決此問題的一種方法是對那里的值進行硬編碼,但我不想這樣做。 相反,有沒有一種方法可以讓“na”遵循順序而無需硬編碼任何值?

注意:請不要修改“#Final Data frame is used below”行上方的數據。 我正在處理的實際數據實際上是相同的格式。 請幫忙。

a1 = c("A","","B","C","D","F")
b1 = c(165,154,134,110,94,78)
a12 = data.frame(a1,b1)
a12[2, 1] = "NA"

#Final Data frame is consumed below
pp1 <<- ggplot(a12 , 
               aes(x = reorder(a1, -b1), 
                   y = b1,
                   text = paste("User: <br>", a1, "<br> Days: <br>", round(b1)))) + 
  geom_bar(stat = "identity", fill = "#3399ff" ) + 
  scale_y_continuous(name = "Time") + 
  scale_x_discrete(name = "Employee") 

ggplotly(pp1, tooltip="text", height = 392)

插件腳本如下:

a1 = c("A",NA,"B","C","D","F")
b1 = c(165,154,134,110,94,78)
a12 = data.frame(a1,b1,stringsAsFactors = FALSE)
pp1 <<- ggplot(a12 , aes(x = reorder(a1,-b1), y = b1,text=paste("User: 
<br>",a1, "<br> Days: <br>", round(b1)))) + 
geom_bar(stat = "identity", fill = "#3399ff" ) + scale_y_continuous(name 
="Time") + scale_x_discrete(name ="Employee") 
ggplotly(pp1, tooltip="text",height = 392)

在此處輸入圖片說明

為了以您想要的方式排列條形,在df$a1不應有缺失值,即NA 我們需要以某種方式替換那個缺失的值。

由於您在上面的評論中要求“不替換,不修改數據” ,我建議您使用例如tidyr::replace_na替換對ggplot調用中的缺失值。 這將使您的原始數據保持不變。

library(tidyr)
library(ggplot2)
pp1 <- ggplot(data = replace_na(a12, replace = list(a1 = "NA")),
                      aes(x = reorder(a1, -b1),
                          y = b1,
                          text = paste("User: <br>", a1, "<br> Days: <br>", round(b1)))) +
  geom_bar(stat = "identity", fill = "#3399ff") +
  scale_y_continuous(name = "Time") +
  scale_x_discrete(name = "Employee")

ggplotly(pp1, tooltip = "text",height = 392)

在此處輸入圖片說明

我希望這有幫助。

暫無
暫無

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

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