如何在 R 中的 Barplot 中的每个条形上添加标签?
在本文中,我们将看到如何使用 R 编程语言在 barplot 中的每个条形上添加标签。
要在 R 中的 Barplot 中的每个条形顶部添加标签,我们使用 ggplot2 包的 geom_text()函数。
Syntax: plot+ geom_text(aes(label = value, nudge_y )
Parameters:
- value: value field of which labels have to display.
- nudge_y: distance shift in the vertical direction for the label
创建一个在条形顶部没有标签的基本条形图:
在下面的示例中,我们将创建数据框,然后使用这个没有标签的数据框绘制条形图。
R
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geek1","Geek2",
"Geek3","Geek4",
"Geeek5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot
plot<-ggplot(sample_data,
aes(name,value)) +
geom_bar(stat = "identity")
plot
R
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geek1","Geek2",
"Geek3","Geek4",
"Geeek5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot with labels
plot<-ggplot(sample_data,
aes(name,value)) +
geom_bar(stat = "identity")+
geom_text(aes(label = signif(value)), nudge_y = 3)
plot
R
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geek1","Geek2",
"Geek3","Geek4",
"Geeek5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot with labels
plot<-ggplot(sample_data,
aes(name,value)) +
geom_bar(stat = "identity")+
geom_text(aes(label = signif(value)), nudge_y = 1) +
geom_text(aes(label = name), nudge_y = 3)
plot
输出:
获取条形顶部的标签
在下面的示例中,我们将在图中添加 geom_text() 以获取每个条形顶部的标签。
电阻
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geek1","Geek2",
"Geek3","Geek4",
"Geeek5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot with labels
plot<-ggplot(sample_data,
aes(name,value)) +
geom_bar(stat = "identity")+
geom_text(aes(label = signif(value)), nudge_y = 3)
plot
输出:
条形顶部的多个标签
通过调整 nudge_y 值,您可以在条形顶部添加多个标签。
电阻
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geek1","Geek2",
"Geek3","Geek4",
"Geeek5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot with labels
plot<-ggplot(sample_data,
aes(name,value)) +
geom_bar(stat = "identity")+
geom_text(aes(label = signif(value)), nudge_y = 1) +
geom_text(aes(label = name), nudge_y = 3)
plot
输出: