问题
I want to create a bar plot with Descending bars, In the plot below, due to NA being present at 2nd spot in "a1" vector, it is pushed at the last when the plot is created. However, I want the NA bar to be present at the 2nd spot only, kindly help me here as I want to achieve this without modifying my data.
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)
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)
回答1:
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)
来源:https://stackoverflow.com/questions/47976994/arranging-bars-of-a-bar-plot-with-null-in-descending-order-in-r