Arranging bars of a bar plot with “null” in Descending order in R

a 夏天 提交于 2019-12-02 02:57:21

In the comments, you argued that hard-coded a value to replace NA is a bad practice. I would say that hard-coded by index position is a bad idea, but automatically replace NA with a character string, such as null, is a good idea.

In the following example, the only thing I added is a12$a1[is.na(a1)] <- "null". This line detects where is NA in a12$a1 and replace it with null. The reorder based on numbers in b1 will happend later, so this approach does not require you to know the index of NA beforehand

library(ggplot2)
library(plotly)

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

# Replace the NA to be "null"
a12$a1[is.na(a1)] <- "null"

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!