调整ggplot2分面饼图的面板标签及坐标轴刻度位置
解决ggplot2多饼图的标签重叠与刻度间距问题
问题1:面板标签与饼图重叠
你的facet标签(如Weed-Community 1)和饼图出现重叠,一是因为饼图占据了面板过多空间,二是标签位置参数设置有误(你之前错误使用了strip.text.y,但横向分面需要调整strip.text.x)。可以通过以下方式解决:
- 缩小饼图宽度,同时扩大x轴范围,给饼图外围留出更多空间
- 调整面板标签的垂直位置和底部边距,让标签远离饼图
修改代码中的绘图部分:
pc <- ggplot(data_of_weeds, aes(x = "", y = Plantdensity, fill = Specie))+ geom_bar(width = 0.8, stat="identity", color = "black") + # 减小bar宽度,让饼图更紧凑 xlim(-1.2, 1.2) + # 扩大x轴范围,给饼图周围预留空间 coord_polar("y", start = 0) + facet_grid(.~ Cluster, labeller = as_labeller(tickname))
然后调整面板标签的样式:
pc1 <- pc + tema_piechart + theme(strip.background.x = element_rect(fill="white"), strip.text.x = element_text(vjust = 2, margin = margin(b = 10))) # 向下移动标签并增加底部边距
问题2:坐标轴刻度与线条贴合过近
y轴刻度(0、50、100、150)与黑色轴线距离过近,只需给刻度标签添加右侧边距即可。在你的tema_piechart主题中修改axis.text.y参数:
tema_piechart <- theme ( panel.background = element_blank(), axis.title.x = element_text(family = "Arial",color = "black"), axis.line = element_line(colour = "black"), text = element_text(size = 20), axis.title.y = element_blank(), axis.ticks.length.y = unit(0, "cm"), legend.position = "none", panel.grid.major = element_line(colour = "black"), axis.text = element_text(color = "black", size = 10), axis.text.y = element_text(margin = margin(r = 8)) # 给y轴刻度标签添加右侧边距,拉开与线条的距离 )
完整修改后的代码
library(ggplot2) library(ggpubr) library(extrafont) library(readxl) Specie <- c("Avena spp", "Avena spp","Avena spp", "Ranunculus spp", "Ranunculus spp", "Ranunculus spp", "Rumex acetosa spp","Rumex acetosa spp","Rumex acetosa spp") Plantdensity <- c(140, 100, 30, 29, 32, 16, 10, 5,2) Cluster <- c("Wc1", "Wc2","Wc3","Wc1", "Wc2","Wc3","Wc1", "Wc2","Wc3") data_of_weeds <- data.frame(Specie, Plantdensity,Cluster) tickname <- c("Wc1" = "Weed-Community 1", "Wc2" = "Weed-Community 2", "Wc3" = "Weed-Community 3") tema_piechart <- theme ( panel.background = element_blank(), axis.title.x = element_text(family = "Arial",color = "black"), axis.line = element_line(colour = "black"), text = element_text(size = 20), axis.title.y = element_blank(), axis.ticks.length.y = unit(0, "cm"), legend.position = "none", panel.grid.major = element_line(colour = "black"), axis.text = element_text(color = "black", size = 10), axis.text.y = element_text(margin = margin(r = 8)) # 调整y轴刻度与线条的距离 ) pc <- ggplot(data_of_weeds, aes(x = "", y = Plantdensity, fill = Specie))+ geom_bar(width = 0.8, stat="identity", color = "black") + # 缩小饼图宽度 xlim(-1.2, 1.2) + # 扩大x轴范围,预留空间 coord_polar("y", start = 0) + facet_grid(.~ Cluster, labeller = as_labeller(tickname)) pc1 <- pc + tema_piechart + theme(strip.background.x = element_rect(fill="white"), strip.text.x = element_text(vjust = 2, margin = margin(b = 10))) # 调整面板标签位置
内容的提问来源于stack exchange,提问作者Claudio Russo
相关产品推荐
相关产品推荐

