gpt4 book ai didi

r - ggplot2中x轴刻度标签的下标和宽度限制

转载 作者:行者123 更新时间:2023-12-02 07:40:49 32 4
gpt4 key购买 nike

Fig 1

这是目前我的上图代码

ggplot(AllData, aes(Year, AGResiduals, fill=Type)) + 
geom_boxplot(outlier.size=0) +
scale_fill_manual(values=c("skyblue4", "skyblue"),
name="Male Type",
labels=c("Guarders","Sneakers")) +
labs(x=NULL, y = "Residual of Accessory Gland Mass x Total Mass") +
scale_x_discrete(limits=c("2007","2008","2010","2011","2013","2014","2015"),
labels=str_wrap(c("2007 (nG=37, nS=8)","2008 (nG=4, nS=6)","2010 (nG=31, nS=6)","2011 (nG=55, nS=5)","2013 (nG=202, nS=24)","2014 (nG=63)","2015 (nG=59, nS=3)"),
width=6)) +
theme(plot.title = element_text(size = rel(1.4)),
axis.title = element_text(size = rel(1.2)),
axis.text.x = element_text(size = rel(1.5)),
axis.text.y = element_text(size = rel(1.5)),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"))

我想使每个 x 轴刻度标签中的“G”和“S”成为下标(它们指定两个不同组 G 和 S 的样本大小)。

写作

expression(2007 (n[G]=37, n[S]=8)

有效,但前提是我删除前面的内容

str_wrap

出于某种原因编码。

我需要限制每个 x 轴刻度标签的文本宽度,因此我需要保留 str_wrap 或以某种方式在表达式函数中使用换行符。

我也无法用一个因素替换我的标签列表,因为我必须对我想要显示的年份设置限制。

有人可以帮忙制作一个允许下标的 3 行 x 轴刻度标签吗?

最佳答案

我找不到在多行上显示表达式的方法,但您可以尝试旋转标签:

library(stringr)
library(ggplot2)
library(scales)
library(dplyr)

n <- 100
y <- as.character(sample(2007:2015,n,replace=T))
t <- sample(c("Guarders","Guarders","Sneakers"),n,replace=T)
r <- rnorm(n,10,20)
nsk <- sum(t=="Sneakers")
r[ t=="Sneakers" ] <- rnorm(nsk,1,5)
AllData <- data.frame(Year=y,AGResiduals=r,Type=t)

sdf <- AllData %>% group_by( Year ) %>%
summarize( n=n(), ng=sum(Type=="Guarders") )

fmts <- rep("%s (n[G]==%d) ~~ (n[S]==%d)",nrow(sdf))
labs2 <- do.call(sprintf,list(fmts,sdf$Year,sdf$ng, sdf$n-sdf$ng ) )

ex2 <- parse(text=labs2)

ggplot(AllData, aes(Year, AGResiduals, fill=Type)) +
geom_boxplot(outlier.size=0) +
scale_fill_manual(values=c("skyblue4", "skyblue"),
name="Male Type",
labels=c("Guarders","Sneakers")) +
labs(x=NULL, y = "Residual of Accessory Gland Mass x Total Mass") +
scale_x_discrete(limits=c("2007","2008","2010","2011","2013","2014","2015"),
labels=ex2) +
theme(plot.title = element_text(size = rel(1.4)),
axis.title = element_text(size = rel(1.2)),
axis.text.x = element_text(size = rel(1.0),angle=-30,hjust=0),
axis.text.y = element_text(size = rel(1.5)),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"))

产生这个: enter image description here

关于r - ggplot2中x轴刻度标签的下标和宽度限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33536382/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com