ggplot中实现图片置于条形图上方及x轴分组标注问题求解
针对两个问题的修改方案如下:
1. x轴分组标识实现
使用ggh4x包的嵌套坐标轴功能,可以直接按照你的ind字段自动划分前3、后3两组,不需要手动校准坐标位置,适配性更强。
2. 队标完整显示调整
- 调整
geom_isotype_col的vjust参数:负值可以让logo向条形图外侧偏移,正数则向条形内部收缩,可根据数值正负设置条件偏移 - 替换原
ylim为scale_y_continuous,通过expand参数给y轴上下预留额外空白,避免logo超出绘图区域被裁剪
修改后的完整代码:
# 提前安装需要的包:install.packages(c("ggh4x", "ggplot2", "ggimage", "magick", "tibble")) library(ggh4x) library(ggplot2) library(ggimage) library(magick) library(tibble) data <- tibble( Diff_home_perc = c(-0.3, -0.2, -0.1,-0.05, 0.2, 0.3), Team = c("A", "B", "C","D", "E", "F"), ind = c("后3名","后3名","后3名","前3名","前3名","前3名"), # 把分组值直接改成要显示的文本 image = list( image_read_svg("https://www.bundesliga.com/assets/clublogo/DFL-CLU-00000G.svg"), image_read_svg("https://www.bundesliga.com/assets/clublogo/DFL-CLU-000017.svg"), image_read_svg("https://www.bundesliga.com/assets/clublogo/DFL-CLU-000018.svg"), image_read_svg("https://www.bundesliga.com/assets/clublogo/DFL-CLU-000003.svg"), image_read_svg("https://www.bundesliga.com/assets/clublogo/DFL-CLU-000004.svg"), image_read_svg("https://www.bundesliga.com/assets/clublogo/DFL-CLU-00000.svg") ) ) ggplot(data, aes(reorder(Team, Diff_home_perc), Diff_home_perc, fill = ind, image = image)) + # 替换原ylim,预留上下15%的空白区域放logo scale_y_continuous(name = "Difference", limits = c(-0.3, 0.3), expand = expansion(mult = 0.15)) + xlab("Team") + # vjust按数值正负调整,负值logo往外放 geom_isotype_col( img_height = NULL, img_width = grid::unit(0.5, "null"), ncol = 1, nrow = 1, hjust = 0.5, vjust = ifelse(data$Diff_home_perc > 0, -0.1, 1.1) ) + # 添加嵌套分组轴 guides(x = "axis_nested") + guides(fill = "none") + theme_minimal() + theme( plot.title = element_blank(), axis.title.x = element_blank(), text = element_text(size=15), legend.title = element_blank(), legend.position="none", # 调整嵌套轴的样式 ggh4x.axis.nestline.x = element_line(linewidth = 1), ggh4x.axis.nesttext.x = element_text(colour = "black") )
如果不想安装额外的包,也可以用annotate函数手动在x轴对应位置添加文本和分割线,只要计算好两组的x轴坐标位置(后3名对应x=1.5位置,前3名对应x=4.5位置)即可。
内容的提问来源于stack exchange,提问作者user15077915
相关产品推荐
相关产品推荐

