如何在R的ggplot2中正确定位X轴标签并设置物种名斜体
ggplot2图表优化:物种名斜体与X轴标签下移
1. 物种名斜体设置(修正拼写+两种实现方式)
你代码里已经用了expression(italic())实现斜体,但注意物种名拼写错误:Criptosporidium应为Cryptosporidium,修正后即可正常显示斜体。
另外推荐更灵活的ggtext包方案,支持markdown语法,无需编写复杂的expression:
- 先安装并加载ggtext:
install.packages("ggtext") library(ggtext)
- 修改
scale_x_discrete的标签为markdown格式,用<br>手动换行:
scale_x_discrete(breaks = c("crypto","kvirus","TLR3"), labels = c("*Cryptosporidium*<br>parvum", "CSPV1", "CSPV1 TLR3"))
- 在
theme中设置X轴文本支持markdown解析:
theme(axis.text.x = element_markdown())
2. X轴标签垂直下移
要将物种名对应的刻度标签向下移动,只需在theme中通过margin参数调整axis.text.x的顶部间距(t值越大,标签下移幅度越大):
theme( axis.text.x = element_text(margin = margin(t = 8)), # 若用ggtext则替换为element_markdown # 如需下移X轴标题"Exact words searched for",添加此行: # axis.title.x = element_text(margin = margin(t = 15)) )
修改后的完整代码(expression版本)
library(ggplot2) v_pub <- 6 #CSPV1 v_gs <- 145 #CSPV1 pub <- 4858 #Cryptosporidium parvum gs <- 69300 #Cryptosporidium parvum vt_pub <- 0 #CSPV1 and TLR3 vt_gs <- 11 #CSPV1 and TLR3 #### GRAPH 1 #### names <- c(rep("crypto",2), rep("kvirus",2), rep("TLR3",2)) source <- c(rep(c("pub","gs"),3)) numbers <- c(pub, gs, v_pub, v_gs, vt_pub, vt_gs) df <- data.frame(names, source, numbers) myplot <- ggplot(df, aes(names, numbers, fill=source)) + geom_bar(stat = "identity", position = 'dodge') + xlab("Exact words searched for") + ylab("Number of papers") + theme_bw() + scale_fill_discrete(name="Database", breaks=c("gs", "pub"), labels=c("Google Scholar", "PubMed")) + geom_text(aes(label = numbers, group=source), position=position_dodge(width=0.9), vjust=-0.2, size=4) + scale_x_discrete(breaks = c("crypto","kvirus","TLR3"), labels = c(expression(italic("Cryptosporidium \nparvum")),"CSPV1","CSPV1 TLR3")) + # 调整X轴刻度标签下移幅度 theme(axis.text.x = element_text(margin = margin(t = 8))) myplot
修改后的完整代码(ggtext版本)
library(ggplot2) library(ggtext) v_pub <- 6 #CSPV1 v_gs <- 145 #CSPV1 pub <- 4858 #Cryptosporidium parvum gs <- 69300 #Cryptosporidium parvum vt_pub <- 0 #CSPV1 and TLR3 vt_gs <- 11 #CSPV1 and TLR3 #### GRAPH 1 #### names <- c(rep("crypto",2), rep("kvirus",2), rep("TLR3",2)) source <- c(rep(c("pub","gs"),3)) numbers <- c(pub, gs, v_pub, v_gs, vt_pub, vt_gs) df <- data.frame(names, source, numbers) myplot <- ggplot(df, aes(names, numbers, fill=source)) + geom_bar(stat = "identity", position = 'dodge') + xlab("Exact words searched for") + ylab("Number of papers") + theme_bw() + scale_fill_discrete(name="Database", breaks=c("gs", "pub"), labels=c("Google Scholar", "PubMed")) + geom_text(aes(label = numbers, group=source), position=position_dodge(width=0.9), vjust=-0.2, size=4) + scale_x_discrete(breaks = c("crypto","kvirus","TLR3"), labels = c("*Cryptosporidium*<br>parvum", "CSPV1", "CSPV1 TLR3")) + theme( axis.text.x = element_markdown(margin = margin(t = 8)) ) myplot
内容的提问来源于stack exchange,提问作者wingardium_leviosa98
相关产品推荐
相关产品推荐

