首页 > 解决方案 > 使用 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 轴在条形顶部显示百分比和频率值。

标签: rggplot2

解决方案


这是您问题的解决方案。了解您是新的贡献者,欢迎!但是请尝试提供一个可重复的示例,说明您在未来的问题中尝试过的内容。

首先创建一个数据框:

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()

情节1

下面的代码将允许您将频率变量粘贴到每个条形图的顶部。

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()

情节2

下面的代码是您正在寻找将 y 轴转换为百分比的代码

scale_y_continuous(labels = scales::percent) +


推荐阅读