How to add numerical values on a bar graph in the R language?
You can add the values on the bar chart using the geom_text() function. The specific steps are as follows:
- To start, calculate the coordinates of the center point of each bar in the bar graph using the position adjustment parameter position = position_stack().
- Next, specify label = …count… in the geom_text() function to display the count value for each bar.
The example code is as follows:
library(ggplot2)
# 创建数据集
data <- data.frame(
category = c("A", "B", "C"),
value = c(10, 20, 30)
)
# 创建条形图
plot <- ggplot(data, aes(x = category, y = value)) +
geom_bar(stat = "identity") +
geom_text(aes(label = ..count..), position = position_stack(vjust = 0.5), stat = "count", size = 5)
plot
After executing the code above, the numerical values of each bar will be displayed on the bar chart. You can also adjust parameters such as font size and color as needed.