用“null"排列条形图的条形图.在R中按降序排列 [英] Arranging bars of a bar plot with "null" in Descending order in R

查看:22
本文介绍了用“null"排列条形图的条形图.在R中按降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个带有降序条的条形图,在下面的图中,由于 NA 出现在a1"向量中的第二个位置,因此在创建图时它被推到最后.但是,我希望 NA 栏只出现在第二个位置,请在这里帮助我,因为我想在不修改数据的情况下实现这一点.

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)

推荐答案

在评论中,您认为硬编码一个值来替换 NA 是一种不好的做法.我想说按索引位置硬编码是个坏主意,但自动将 NA 替换为字符串,例如 null,是个好主意.

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.

在以下示例中,我添加的唯一内容是 a12$a1[is.na(a1)] <- "null".此行检测 a12$a1NA 的位置并将其替换为 null.基于b1中数字的reorder会在后面发生,所以这种方法不需要你事先知道NA的索引

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)

这篇关于用“null"排列条形图的条形图.在R中按降序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆