如何在R中使用ggplot2创建具有相同宽度条形图的不同类别的多个条形图?
为了使用ggplot2创建具有相同宽度条形图的不同类别的多个条形图,我们需要在geom_bar函数内部使用width参数来匹配每个条形图中条形的宽度。最好的方法是将较长的条形宽度设置为0.25,较短的条形宽度设置为0.50。
示例
考虑以下数据框:
x1<-c("A","B") y1<-c(21,23) df1<-data.frame(x1,y1) df1
输出
x1 y1 1 A 21 2 B 23
加载ggplot2包并为x1中的类别创建条形图:
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
library(ggplot2) plot1<-ggplot(df1,aes(x1,y1))+geom_bar(stat="identity",width=0.25) plot1
输出
考虑另一个包含更多类别的数框:
x2<-c("A","B","C","D") y2<-c(21,24,25,23) df2<-data.frame(x2,y2)
创建x2中类别的条形图,使其与plot1中条形的宽度匹配:
示例
plot2<-ggplot(df2,aes(x2,y2))+geom_bar(stat="identity",width=0.5) plot2
输出
广告