在安排R和ggplot2中条形图中的条形时出现“na”问题

问题描述 投票:-1回答:1

我正在尝试使用ggplot2创建一个降序条形图,并在R中绘制图形。我使用的数据是“a12”,它由ggplot在“#Final Data frame is below below below”行下使用。

如果你看到下面的快照,“a1”列中的“na”值应该出现在图中的第二个位置,但是它不按降序排列并且在最后一个位置被推动。

解决这个问题的一种方法是在那里硬编码值,但我不想这样做。相反,有没有一种方法,我可以使“na”遵循顺序而不硬编码任何值?

注意:请不要修改“#Final Data frame is below below 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)

enter image description here

r ggplot2 plotly geom-bar ggplotly
1个回答
1
投票

为了按照你想要的方式排列条形,在NA中不应该有缺失值,即df$a1。我们不知何故需要替换那个缺失值。

由于您在上面的评论中要求“无替换,不对数据进行修改”,我建议您使用例如ggplot替换调用中的缺失值。 tidyr::replace_na。这将使原始数据保持不变。

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)

enter image description here

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.