在R中的数据框中创建值的条形图

时间:2020-03-04 18:33:16

标签: r dataframe histogram

假设我有以下数据框

result-view {
  match: AltBrainsData (this) 
  { 
  from-output: GetAltBrainsData (getaltbrainsdata)
  }

  message {

    //here is where i want to check if UserData.newuser = true and vary the answer
  //if (userdata.newuser) {template("hello new user")} else ...


    if (size(this) > 1) {
    template ("I found #{(size(this))} AltBrains")
    }
    else-if (size(this) == 1 ) {
    template ("") {speech ("#{value(this.name)}")}
    }
    else {template ("No AltBrains matched the search.")}
     }

  render {

    // if UserData.newuser = true then welcome layout

我想创建一个数据框中的值的条形图(即显示总共有0、1、2、3个数)。

但是

set.seed(85)
a <- data.frame(replicate(10,sample(0:3,5,rep=TRUE)))

给我错误hist(a) ,但是'x' must be numeric给我错误as.numeric(a)

如何绘制数据框中的值的条形图?最好也应忽略N / A值。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

用图形表示“总共有0、1、2、3个” 是表示这些值的计数。因此,合适的图形类型是 barplot ,而不是直方图。

barplot(table(unlist(a)))

enter image description here

如果数据已更改为将a的所有元素都等于一个值,在这种情况下将"2"替换为NA,则解决方案可能是强制因素手动设置水平。

a[a == "2"] <- NA
a2 <- unlist(a)
a2 <- factor(a2, levels = min(a2, na.rm = TRUE):max(a2, na.rm = TRUE))
barplot(table(a2))

enter image description here

ggplot2

此外,在this other answer中有一个ggplot解决方案不正确。我已经在评论中提出了一个更正建议,但是我还没有答案,并且所提出的更正要求也适用于这种情况,而无需强制考虑。

library(ggplot2)

ggplot(stack(a), aes(x = values)) + 
  geom_bar()

enter image description here

答案 1 :(得分:0)

直方图以及ggplot2中的geom_histogram用于连续数据。您需要一个条形图以可视化离散数据。除了图形中的条形图,您还可以在ggplot2中使用geom_bar。 ggplot2语法为:

library(ggplot2)
set.seed(85)
a <- data.frame(replicate(10,sample(0:3,5,rep=TRUE)))
ggplot(stack(a)) + geom_bar(aes(x=values))