r - 使用 ggplot 创建条形图
问题描述
我对 R 有点陌生,我在 ggplot 上挣扎了很长一段时间。
我有一个数据框,如下所示:
x Freq
1 81
2 36
3 29
4 11
5 9
6 10
7 10
8 4
9 6
>10 49
我想得到这样的条形图:
但我希望 y 轴在条形顶部显示百分比和频率值。
解决方案
这是您问题的解决方案。了解您是新的贡献者,欢迎!但是请尝试提供一个可重复的示例,说明您在未来的问题中尝试过的内容。
首先创建一个数据框:
set.seed(101)
#create dataframe
df <- data.frame(x = 1:10, Freq = sample(1:100, 10))
获取百分比列的方法有很多,您可以使用提供的 2 种方法创建它,也可以直接跳转到 ggplot2 方法:
#create a percent of column
df$Freq_percent <- round(((df$Freq/ sum(df$Freq)) * 100), 2) #Method 1
df
x Freq Freq_percent
1 1 38 8.94
2 2 5 1.18
3 3 70 16.47
4 4 64 15.06
5 5 24 5.65
6 6 29 6.82
7 7 55 12.94
8 8 32 7.53
9 9 58 13.65
10 10 50 11.76
方法二:使用 dplyr
df <- dplyr::mutate(df, Freq_percent_dplyr = (Freq / sum(Freq))*100) #Method 2
df
x Freq Freq_percent_dplyr
1 1 38 8.941176
2 2 5 1.176471
3 3 70 16.470588
4 4 64 15.058824
5 5 24 5.647059
6 6 29 6.823529
7 7 55 12.941176
8 8 32 7.529412
9 9 58 13.647059
10 10 50 11.764706
绘制条形图:
library(ggplot2)
ggplot(df, aes(x=x, y=Freq_percent)) +
geom_bar(stat='identity') +
geom_text(aes(label=paste("Freq:", Freq)), vjust=0) +
scale_x_continuous(breaks = c(1:10)) +
theme_classic()
下面的代码将允许您将频率变量粘贴到每个条形图的顶部。
geom_text(aes(label=paste("Freq:", Freq)), vjust=0)
无需事先操作数据框即可获得 Y 轴百分比的方法:
ggplot(df, aes(x=x, y=Freq)) +
geom_bar(stat='identity') +
geom_text(aes(label=paste("Freq:", Freq)), vjust=0) +
scale_y_continuous(labels = scales::percent) +
scale_x_continuous(breaks = c(1:10)) +
theme_classic()
下面的代码是您正在寻找将 y 轴转换为百分比的代码
scale_y_continuous(labels = scales::percent) +
推荐阅读
- android - 如何使用项目recyclerView的位置来恢复评论
- java - Java中检查密码的方法不起作用
- php - 如何检查GET是否为空?
- python - 在单行文本文件中的数字后添加新行
- wordpress - 自定义 404 和搜索结果未显示
- c# - 在 Web API 中启用了 CORS,但访问被拒绝
- python - 如何在 python 的矩阵中交换列表?
- reporting-services - Reporting Services KPI 的自定义颜色
- regex - 批处理窗口中的正则表达式
- javascript - Facebook SDK FB.GetLoginStatus 加载被 X-Frame-Options 拒绝(仅限 Firefox)