【问题标题】:ggplot and ggvis for numeric vector in RR中数字向量的ggplot和ggvis
【发布时间】:2026-02-18 01:35:02
【问题描述】:

我有一个数字向量 counts,它存储了来自多个表 list 的列的总数。

所以head(counts) 给出:

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

1000 是表 1 的值,1000 是表 2 的值,40 是表 3 的值,依此类推。

head(list) 给出:

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

当我做barplot(counts) 时,我得到一个条形图。但我无法使用ggvisggplot 绘制条形图。对于 ggplot 我收到此错误:

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

所以我将其转换为data.frame 并将其存储为新变量:

newdata <- data.frame(counts,list)

当我做head(newdata) 时,我得到了这个:

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

但是当我尝试使用 ggvis 绘制条形图时出现错误:

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" ...)

如果我画一个 ggplot ggplot(newdata, aes(x = list, y = counts)) 我会得到一个空白图表。有什么想法吗?

【问题讨论】:

    标签: r vector ggplot2 numeric ggvis


    【解决方案1】:

    带有ggplot的条形图

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

    带有ggvis的条形图

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

    【讨论】: