我想通过使用sample()从数字1到20进行100次采样(并替换),然后将此数据转换为数据框并可视化。
df <- sample(1:20, 100, replace=TRUE) df <- as.data.frame(df) ggplot(df, aes(x= df, y= n)) + geom_bar(position = "fill")
试图找到一种更好的方法将sample()数据转换为数据帧。谢谢
不确定您的意思是更好的方法,但我想您可以做到
library(ggplot2) df <- data.frame(x = sample(1:20, 100, replace=TRUE)) ggplot(df, aes(x)) + geom_bar()
或直接使用
ggplot(data.frame(x = sample(1:20, 100, replace=TRUE)), aes(x)) + geom_bar()
一个更好的选择是利用tidyverse
tidyverse
library(dplyr) library(ggplot2) tibble(x = sample(1:20, 100, replace = TRUE)) %>% ggplot(aes(x)) + geom_bar()
在base R中,我们可以执行此操作而无需创建data.frame
base R
barplot(sample(1:20, 100, replace = TRUE))