我有一个像这样的数据集(df):
| 年龄 | n |
|---|---|
| 18 | 2500 |
| 19 号 | 1200 |
| 20 | 4500 |
| 21 | 800 |
| 23 | 120 |
| 24 | 50 |
| 25+ | 100 |
我创建了一个像这样的代码的ggplot,它按年龄显示学生群体
ggplot(df, aes(x=Age, y=n)) +
geom_bar(stat="identity") + ggtitle("Student Body by Age at ETH in the assesment year") + scale_y_continuous(labels = function(x) format(x, scientific = FALSE))
Run Code Online (Sandbox Code Playgroud)
现在我想在直方图旁边创建一个图例,显示按年龄划分的评估年份的成功率。有了这些数据集
| 年龄 | % 成功 |
|---|---|
| 18-19日 | 80 |
| 20-21日 | 60 |
| 23-24日 | 50 |
| 25+ | 20 |
有没有代码可以添加带有年龄成功率的图例?
直方图很好,但我想要一个图例,在右侧显示按年龄划分的成功率。
您所描述的实际上并不是 ggplot 意义上的图例,但可以通过在图例通常所在的位置添加一个表来实现。使用与@langtang相同的数据名称,我们可以这样做:
library(ggpubr)
library(patchwork)
ggplot(df, aes(x=Age, y=n)) +
geom_bar(stat="identity") +
ggtitle("Student Body by Age at ETH in the assesment year") +
scale_y_continuous(labels = function(x) format(x, scientific = FALSE)) +
ggtexttable(success_rates, rows = NULL, theme = ttheme("light")) +
plot_layout(widths = 2:1)
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2022 年 7 月 31 日创建(v2.0.1)
| 归档时间: |
|
| 查看次数: |
760 次 |
| 最近记录: |