SuSuYu
@SuSuYu

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

ggplot2でfacet_gridで分割されたグラフそれぞれにgeom_textで文字を入力する方法

解決したいこと

R,Rstudio初心者です.ggplot2を用いてグラフを作成しています.
以下のようにパターンごとに分割したグラフの作成までは成功したのですが,分割したグラフそれぞれの右上に「A」「B」「C」のような対応するラベルをつけようとしたところ,エラーが出て先に進まず,頭を悩ませております.
どうにかRstudio,ggplot2を使用してそれぞれにラベルをつけたいのですが,手詰まり状態のため,ご教示いただけますと幸いです.

Rstudioのバージョンは 2024.09.0 Build 375 です.

Rplot.png

使用したデータセットの例

データセット名: answeredscore
Rstudioでエクセルからインポートして使用

ID	    Pattern	Group	 Condition	Score
HC	    Pa1	    Healthy	 Ne	        9
HC	    Pa2   	Healthy	 Ne      	9
HC	    Pa3  	Healthy	 Ne     	9
P001	Pa3 	Patient  Ne     	7
P002	Pa1 	Patient  Ne     	4
P005	Pa2 	Patient	 Ne     	10
P006	Pa1 	Patient	 Ne     	7
HC	    Pa1	    Healthy	 Fa     	5
HC	    Pa2	    Healthy	 Fa     	5
HC	    Pa3	    Healthy	 Fa     	5
P001	Pa3	    Patient	 Fa     	12
P002	Pa1  	Patient	 Fa     	14
P005	Pa2 	Patient	 Fa     	13
P006	Pa1 	Patient	 Fa     	2

グラフ作成に使用したコード

library(ggplot2)
library(lemon)

answeredscore2 <- transform(answeredscore, Condition = factor(Condition, levels = c("Ne", "Fa")))

g2 <- ggplot(answeredscore2, aes(x = Condition, y = Score, group = ID, linetype = Group), label = ID) +
  geom_line(lwd = 1) +
  geom_text(data = subset(subset (answeredscore2, ID != "HC"), Condition == "Fa"),
            aes(label = ID), size = 3.5, 
            nudge_x = 0.2) +
  scale_linetype_manual(values = c("dashed", "solid")) +
  scale_x_discrete(labels = c("Time1", "Time2")) +
  ylab("Answerd Score") +
  scale_y_continuous(limits = c(0.0, 15.0), breaks = seq(0.0, 15.0, 3.0)) +
  theme_classic() +
  theme(axis.title.x = element_blank(), 
        axis.title.y = element_text(size = 16),
        axis.text.x = element_text(size = 13),
        axis.text.y = element_text(size = 13),
        legend.title = element_blank(), 
        strip.text = element_blank(), 
        legend.position = "none") +
  facet_rep_grid(.~Pattern, repeat.tick.labels = TRUE) 

P_labels <- data.frame(Pattern = c("Pa1", "Pa2", "Pa3"), labeltext = c("A", "B", "C"))

g2 + geom_text(x = 2, y = 15, data = P_labels, aes(label = labeltext))

g2

エラー

Error in `geom_text()`:
! Problem while computing aesthetics.
 Error occurred in the 3rd layer.
Caused by error:
! オブジェクト 'ID' がありません
Run `rlang::last_trace()` to see where the error occurred.
0

4Answer

This answer has been deleted for violation of our Terms of Service.

Your answer might help someone💌