如何在R数据框中为离散列创建直方图?
要为R数据框中的离散列创建直方图,我们可以使用ggplot2包的geom_bar函数,并将宽度设置为1,并在aes中传递相同的列作为x和y。
例如,如果我们有一个名为df的数据框,其中包含一个名为x的离散列,那么可以使用以下命令创建x中数据的直方图:
ggplot(df,aes(x,x))+geom_bar(stat="identity",width=1)
示例
以下代码片段创建了一个示例数据框:
x<-rpois(2000,5) df<-data.frame(x) head(df,20)
输出
创建了以下数据框:
x 1 8 2 4 3 3 4 2 5 5 6 6 7 4 8 5 9 7 10 4 11 1 12 5 13 6 14 8 15 4 16 3 17 1 18 5 19 6 20 4
现在,要加载ggplot2包并为x中的数据创建直方图,请将以下代码添加到上述代码片段中:
library(ggplot2) ggplot(df,aes(x,x))+geom_bar(stat="identity",width=1)
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果将以上所有代码片段作为单个程序执行,则会生成以下输出:
广告