簡體   English   中英

在圖外設置圖例的方法

[英]Method for setting the legend outside a plot

到目前為止,我所見過的所有解決方案都包括手動設置圖例的坐標,使其位於圖的外部。 我有> 100個圖,因此希望能夠在每個圖上重用相同的代碼,以默認將圖例放置在圖外。

這里有兩個數據框架,一個是成功的求職者,另一個是所有申請該職位的人:

Id <- c(1,5,7,9,11,12,13,15,17,18)
Type <- c("Beginner", "Expert", "Intermediate", "Beginner", 
"Professional", "Expert", "Intermediate", "Professional", "Professional", 
"Expert")
Response<- c(0,1,2,2,1,2,1,2,1,1)
Successful <- data.frame(Id, Type, Response)
Successful

#   Successful
Id  Type             Response    
1   Beginner         0
5   Expert           1
7   Intermediate     2
9   Beginner         2
11  Professional     1
12  Expert           2
13  Intermediate     1
15  Professional     2
17  Professional     1
18  Expert           1

Id <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18)
Type <- c("Beginner", "Expert", "Professional", "Beginner", "Expert", 
"Expert", "Intermediate", "Expert", "Beginner", "Intermediate", 
"Professional", "Expert", "Intermediate","Intermediate", "Professional", 
"Beginner", "Professional","Expert")
Response<- c(0,2,2,1,1,0,2,0,2,0,1,2,1,1,2,2,1,1)
AllApplicants <- data.frame(Id, Type, Response)
AllApplicants

#   AllApplicants
Id  Type             Response        
1   Beginner         0
2   Expert           2
3   Professional     2
4   Beginner         1
5   Expert           1
6   Expert           0
7   Intermediate     2
8   Expert           0
9   Beginner         2
10  Intermediate     0
11  Professional     1
12  Expert           2
13  Intermediate     1
14  Intermediate     1
15  Professional     2
16  Beginner         2
17  Professional     1
18  Expert           1

如果我們繪制此數據的圖:

colors <- c("red", "orange", "green")
barplot(round(100*prop.table(table(AllApplicants$Response, 
AllApplicants$Type),2), 1),
    main="Responses of applicants", xlab="Level", ylab= "Proportion", 
    col=colors, legend.text = T)

圖例顯示與情節重疊。 我知道可以手動設置圖形的邊距和圖例的位置:

par(mar=c(5.1,4.1,4.1,8))
legend(5,90, legend=c(0,1,2), fill=colors, xpd=T)

但是,如果我在barplot()函數中包含legend.text = TRUE,我希望保留自動生成的圖例,並使其自動將圖例放在圖的右側和右側。 調整圖的大小和縮放時,我還需要將其保持在該位置。

任何幫助將不勝感激!

ggplot2解決方案可以工作嗎?

library(ggplot2)

df <- as.data.frame(round(100*prop.table(table(AllApplicants$Response, AllApplicants$Type),2), 1))

ggplot(df, aes(x=Var2, y=Freq)) + 
geom_col(aes(fill=Var1)) + 
ggtitle("Responses of applicants") + 
theme(plot.title = element_text(hjust=0.5)) + 
xlab("Level") + ylab("Proportion") + 
theme(legend.title = element_blank())

圖片

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM