[英]Adding images below x-axis labels in ggplot2
I have this plot:我有这个 plot:
Which has been produced with this code chunk based on an old TidyTuesday dataset, Astronaut.该代码块是基于旧的 TidyTuesday 数据集 Astronaut 生成的。
library(tidyverse)
library(ggplot2)
library(ggtext)
astro_Q2_final %>%
ggplot(aes(x = reorder(nationality, proportion), y = proportion)) +
geom_col() +
theme_minimal() +
geom_text(aes(label = round(proportion, 3)), position = position_dodge(width = 0.9),
vjust = -0.25) +
labs(title = "Proportion of Space Travellers who are Female, by Nationality",
x = "Nationality",
y = "Proportion of Female Astronauts")
The data itself is quite simple - character variable of nationality on the x-axis, and an integer variable corresponding to a worked-out proportion on the y.数据本身非常简单 - x 轴上的国籍字符变量,以及对应于 y 上计算出的比例的 integer 变量。 All I want to do is add images of the flags of the nationalities on the x-axis above the country names.我要做的就是在国家名称上方的 x 轴上添加民族国旗的图像。 I have tried this photo alignment with graph in r but with no luck;我试过这张照片 alignment 和 r 中的图表,但没有运气; I think it's something to do with the fact that Claus Wilke creates the data
object with the expand.grid
function - I can't seem to translate what he's doing to what I need to do with my plot/data.我认为这与 Claus Wilke 使用expand.grid
function 创建data
object 的事实有关 - 我似乎无法将他正在做的事情转化为我需要对我的绘图/数据做的事情。 Any help would be much appreciated.任何帮助将非常感激。
The data can be found herehttps://raw.githubusercontent.com/gjpstrain/astro/main/data.csv数据可以在这里找到https://raw.githubusercontent.com/gjpstrain/astro/main/data.csv
So I've had another look at the ggtext documentation and have included this:因此,我又查看了 ggtext 文档并将其包括在内:
labels <- c(
U.S.S.R/Russia = "<img src = 'Russia.png' width = 100' /><br>USSR/Russia",
China = "<img src = 'China.jpg' width = '100' /><br>China",
Italy = "<img src = 'Italy.png' width = '100' /><br>Italy",
France = "<img src = 'France.jpg' width = '100' /><br>France",
U.S = "<img src = 'US.png' width = '100' /><br>US",
Japan = "<img src = 'Japan.png' width = '100' /><br>Japan",
Canada = "<img src = 'Canada.png' width = '100' /><br>Canada",
U.K = "<img src = 'UK.png' width = 100' /><br>UK",
Korea = "<img src = 'South-Korea.jpg' width = '100' /><br>Korea")
However when I try this:但是,当我尝试这个时:
astro_Q2_final %>%
ggplot(aes(x = reorder(nationality, proportion), y = proportion)) +
geom_col() +
scale_x_discrete(name = NULL,
labels = labels)
I get我明白了
Load library ggtext
and add this line in the last加载库ggtext
并在最后添加这一行
astro_Q2_final %>%
ggplot(aes(x = reorder(nationality, proportion), y = proportion)) +
geom_col() +
scale_x_discrete(name = NULL,
labels = labels) +
theme(axis.text.x = ggtext::element_markdown())
You should get the desired visual, if the image-links are correct.如果图像链接正确,您应该获得所需的视觉效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.