如何用 R 语言创建一个包含正负值的条形图?
要创建包含正负值的条形图,我们可以使用 ggplot 函数。
例如,如果我们有一个名为 df 的数据框,其中包含一个分类列(比如 C)和一个数值列(比如 Num,其中包含一些正值和一些负值),那么可以使用以下命令创建此数据的条形图 −
ggplot(df,aes(C,Num))+geom_bar(stat="identity")
示例
以下是创建示例数据框的代码 −
Category<-c("Egypt","Sudan","Turkey","Indonesia") Response_Score<-c(10,-2,4,-5) df<-data.frame(Category,Response_Score) df
输出
创建以下数据框 −
Category Response_Score 1 Egypt 10 2 Sudan -2 3 Turkey 4 4 Indonesia -5
要加载 ggplot2 包并为存储在 df 中的数据创建条形图,请将以下代码添加到上面的代码段中 −
library(ggplot2) ggplot(df,aes(Category,Response_Score))+geom_bar(stat="identity")
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果你将以上所有代码段作为一个单独的程序执行,它将生成以下输出 −
广告