如何在R中使用ggplot2建立的條形圖中水平對齊文字?


為了在使用R中ggplot2建立的條形圖中水平對齊文字,我們可以按照以下步驟操作:

  • 首先,建立一個數據框。

  • 然後,使用ggplot2建立條形圖,並在每個條形上顯示文字。

  • 之後,建立具有水平對齊文字的相同條形圖。

建立資料框

讓我們建立一個如下所示的資料框:

 線上演示

Category<-c("First","Second","Third")
Count<-c(21,25,27)
df<-data.frame(Category,Count)
df

執行上述指令碼後,將生成以下輸出(由於隨機化,此輸出會在您的系統上有所不同):

輸出

 Category Count
1 First    21
2 Second   25
3 Third    27

建立在每個條形上顯示文字的條形圖

使用annotate函式建立在每個條形上顯示文字的條形圖:

Category<-c("First","Second","Third")
Count<-c(21,25,27)
df<-data.frame(Category,Count)
library(ggplot2)
ggplot(df,aes(Category,Count))+geom_bar(stat="identity")+scale_y_continuous(limits=c
(0,30))+annotate("text",x=1:3,y=c(21,25,27),label=c("I","II","III"))

輸出

建立在每個條形上水平顯示文字的條形圖

透過將y值設定為Inf,使用annotate函式建立在每個條形上水平顯示文字的條形圖:

Category<-c("First","Second","Third")
Count<-c(21,25,27)
df<-data.frame(Category,Count)
library(ggplot2)
ggplot(df,aes(Category,Count))+geom_bar(stat="identity")+scale_y_continuous(limits=c
(0,30))+annotate("text",x=1:3,y=Inf,vjust=1.5,label=c("I","II","III"))

輸出

更新於:2021年8月11日

453 次檢視

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.