Search code examples
rvectorggplot2numericggvis

ggplot and ggvis for numeric vector in R


I have a numeric vector counts which stores a total count of a column from several tables list.

so head(counts) gives:

head(counts)
## [1] 1000 1000   40 1000 1000  624

1000 is value for table1, 1000 for table2, 40 for table 3 and so on.

and head(list) gives:

head(list)
## [1] "table1"        "table2"    "table3"
## [4] "table"         "table"     "table6"

when I do barplot(counts) I get a barplot. But I can't draw a barplot using ggvis or ggplot. For ggplot I get this error:

ggplot2 doesn't know how to deal with data of class numeric.  

so I converted it to data.frame and store it as a new variable:

newdata <- data.frame(counts,list)

when I did head(newdata) I got this:

##   counts             list
## 1   1000             table1
## 2   1000             table2
## 3     40             table3

but when I try to draw a barplot using ggvis I get an error:

ggvis(newdata, props(x = ~list, y = ~counts, y2 = 0)) +
  mark_rect(props(width := 10))
error in new_prop.default... : unknown input to pro: list(property = "x" ...)

and if I draw a ggplot ggplot(newdata, aes(x = list, y = counts)) I get a blank graph. Any idea?


Solution

  • barplot with ggplot

    library(ggplot2)
    ggplot(newdata, aes(x = list, y = counts)) + geom_bar(stat = "identity")
    

    enter image description here

    barplot with ggvis

    library(ggvis)
    newdata %>% ggvis(~list, ~counts) %>% layer_bars()
    

    enter image description here