在 R 中的 ggplot2 中的堆积条形图上显示数据值
在本文中,您将学习如何在堆积条形图上显示数据值 ggplot2 在 R 编程语言中。
要将数据显示到堆积条形图中,您必须使用另一个名为geom_text() 的参数。
句法:
geom_text(size, position = position_stack(vjust = value), colour)
这里的大小表示将出现在绘图上的字体大小,而 position_stack() 将自动将值添加到绘图的相应位置。
示例 1:
R
# Creating the Data
Subject = c(rep(c("Hindi", "English", "Math", "Science",
"Computer Science"), times = 4))
Year = c(rep(c("2017-18", "2018-19", "2019-20",
"2020-21"), each = 5))
Students_Passed = c(67,34,23,66,76,66,90,43,45,78,54,73,
45,76,88,99,77,86,56,77)
# Passing the Data to DataFrame
Students_Data = data.frame(Subject,Year,Students_Passed)
# loading the Library
library(ggplot2)
# Plotting the Data in ggplot2
ggplot(Students_Data, aes(x = Year, y = Students_Passed,
fill = Subject, label = Students_Passed)) +
geom_bar(stat = "identity") + geom_text(
size = 3, position = position_stack(vjust = 0.5))
R
# Creating the Data
Subject = c(rep(c("Hindi", "English", "Math", "Science",
"Computer Science"), times = 4))
Year = c(rep(c("2017-18", "2018-19", "2019-20",
"2020-21"), each = 5))
Students_Passed = c(67,34,23,66,76,66,90,43,45,78,54,
73,45,76,88,99,77,86,56,77)
# Passing the Data to DataFrame
Students_Data = data.frame(Subject,Year,Students_Passed)
# loading the Library
library(ggplot2)
# Plotting the Data in ggplot2
ggplot(Students_Data, aes(x = Year, y = Students_Passed,
fill = Subject, label = Students_Passed)) +
geom_bar(stat = "identity") + geom_text(
size = 5, position = position_stack(vjust = 0.5),colour = "white")
输出:
也可以使用 geom_text() 本身更改数据值的颜色。为此,只需将字体颜色传递给颜色属性。
示例 2:
电阻
# Creating the Data
Subject = c(rep(c("Hindi", "English", "Math", "Science",
"Computer Science"), times = 4))
Year = c(rep(c("2017-18", "2018-19", "2019-20",
"2020-21"), each = 5))
Students_Passed = c(67,34,23,66,76,66,90,43,45,78,54,
73,45,76,88,99,77,86,56,77)
# Passing the Data to DataFrame
Students_Data = data.frame(Subject,Year,Students_Passed)
# loading the Library
library(ggplot2)
# Plotting the Data in ggplot2
ggplot(Students_Data, aes(x = Year, y = Students_Passed,
fill = Subject, label = Students_Passed)) +
geom_bar(stat = "identity") + geom_text(
size = 5, position = position_stack(vjust = 0.5),colour = "white")
输出