如何在 R 中使用 ggplot2 在条形图中将文本显示在中间?
要在 R 中使用 ggplot2 在条形图中央显示文本,我们可以按照下列步骤操作:-
首先,创建一个数据框。
然后,使用 ggplot 函数和 geom_bar 函数创建条形图,并使用 geom_text 函数在中间显示文本
示例
创建数据框
让我们创建一个如下所示的数据框:-
x<-LETTERS[1:4] freq<-c(24,28,21,30) df<-data.frame(x,freq) df
输出
执行后,以上脚本会生成以下输出(此输出会因系统中的随机性而异):-
x freq 1 A 24 2 B 28 3 C 21 4 D 30
创建条形图并在中央显示文本
使用 ggplot 函数和 geom_bar 函数创建数据框 df 中存储的数据的条形图,并使用 geom_text 函数在条形中央显示 freq 列的文本:-
x<-LETTERS[1:4] freq<-c(24,28,21,30) df<-data.frame(x,freq) library(ggplot2) ggplot(df,aes(x,freq))+geom_bar(stat="identity")+geom_text(aes(label=freq),color="white",size=5,position=position_stack(vjust=0.5))
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
广告