我正在嘗試制作一個帶有注釋的分組箱線圖,顯示每組中的行數,但我似乎無法讓它作業
我創建了這個例子來說明問題
#define variables
bin=rep(c('A', 'B', 'C'), each=50)
category=rep(c('small', 'large'), each=25)
val=seq(1:150) sample(1:100, 100, replace=TRUE)
#create dataset using variables
df=data.frame(bin, category, val)
它有 150 行,分為箱和類別
#view top rows of dataframe
head(df)
bin category val
1 A small 93
2 A small 100
3 A small 16
4 A small 66
5 A small 9
6 A small 69
我使用 tidyverse 制作帶有注釋資訊的資料框
library(tidyverse)
# count bin and category
countBinCat <-df %>%
group_by(bin, category) %>%
summarize(count= sum(!is.na(val)))
# make the data for the annotations
box_annot <- data.frame(
x = c(0.8, 1.2, 1.8, 2.2, 2.8, 3.2),
y = c(10, 10, 10, 10, 10, 10),
label = c(
countBinCat$count[1],
countBinCat$count[2],
countBinCat$count[3],
countBinCat$count[4],
countBinCat$count[5],
countBinCat$count[6]
)
)
使用所有這些,我可以制作一個分組箱線圖或有標簽,但如果我嘗試同時擁有這兩者,我會收到錯誤訊息:
# Chart 1
# works with groups but no label
ggplot(df, aes(x=bin, y=val, fill=category))
geom_boxplot()
# Chart 2 -
# works with labels but no groups
ggplot(df, aes(x=bin, y=val))
geom_boxplot()
geom_text(data=box_annot, aes(label=paste('n=',label,sep=''), y = y, x=x))
#Chart 3 -
# fails with both
ggplot(df, aes(x=bin, y=val, fill=category))
geom_boxplot()
geom_text(data=box_annot, aes(label=paste('n=',label,sep=''), y = y, x=x))
圖表 1 和 2 作業,第三個給出以下錯誤:
Error in `check_aesthetics()`: ! Aesthetics must be either length 1 or the same as the data (6): x and fill
如何在圖表上同時獲得組和標簽?
uj5u.com熱心網友回復:
在圖 3 中,只需移動fill = category內部geom_boxplot(),它應該可以作業。
ggplot(df, aes(x=bin, y=val))
geom_boxplot(aes(fill=category))
geom_text(data=box_annot, aes(label=paste('n=',label,sep=''), y = y, x = x))

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535927.html
標籤:r图表2
