如何在ggplot2中的直方图上显示百分比
您可以使用以下基本语法在 ggplot2 中的直方图 y 轴上显示百分比:
library (ggplot2) library (scales) #create histogram with percentages ggplot(data, aes (x = factor (team))) + geom_bar( aes (y = (..count..)/ sum (..count..))) + scale_y_continuous(labels=percent)
以下示例展示了如何在实践中使用此语法。
示例 1:带有百分比的基本直方图
以下代码演示如何为分类变量创建直方图,并在 Y 轴上显示百分比:
library (ggplot2) library (scales) #define data frame data <- data. frame (team = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C') , points = c(77, 79, 93, 85, 89, 99, 90, 80, 68, 91, 92)) #create histogram with percentages ggplot(data, aes (x = factor (team))) + geom_bar( aes (y = (..count..)/ sum (..count..))) + scale_y_continuous(labels=percent)
示例 2:带百分比的直方图(删除小数)
您还可以使用precision参数在 y 轴上仅将整数显示为百分比:
library (ggplot2) library (scales) #define data frame data <- data. frame (team = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C') , points = c(77, 79, 93, 85, 89, 99, 90, 80, 68, 91, 92)) #create histogram with percentages ggplot(data, aes (x = factor (team))) + geom_bar( aes (y = (..count..)/ sum (..count..))) + scale_y_continuous(labels = scales :: percent_format(accuracy = 1L ))
示例 3:带有百分比的自定义直方图
以下代码演示如何创建在 Y 轴上显示百分比以及自定义标题、轴标签和颜色的直方图:
library (ggplot2) library (scales) #define data frame data <- data. frame (team = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C') , points = c(77, 79, 93, 85, 89, 99, 90, 80, 68, 91, 92)) #create histogram with percentages and custom aesthetics ggplot(data, aes (x = factor (team))) + geom_bar( aes (y = (..count..)/ sum (..count..)), fill = ' lightblue ') + scale_y_continuous(labels=percent) + labs(title = ' Breakdown by Team ', x = ' Team ', y = ' Percent of Total ') + theme_minimal()
其他资源
以下教程解释了如何在 R 中使用直方图进行其他常见操作: