如何避免在 R 中的 ggplot2 中重叠标签?
在本文中,我们将了解如何在 R 编程语言中避免 ggplot2 中的标签重叠。
为了避免 ggplot2 中的标签重叠,我们在 scale_x_discrete( )中使用了 guide_axis ()。
Syntax: plot+scale_x_discrete(guide = guide_axis(
In the place of we can use the following properties:
- n.dodge: It makes overlapping labels shift a step-down.
- check.overlap: This removes the overlapping labels and displays only those which do not overlap
创建带有重叠标签的基本条形图
R
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geeksforgeeks1",
"Geeksforgeeks2",
"Geeksforgeeks3",
"Geeksforgeeks4",
"Geeeksforgeeks5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot
plot<-ggplot(sample_data, aes(name,value, fill=name)) +
geom_bar(stat = "identity")
plot
R
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geeksforgeeks1",
"Geeksforgeeks2",
"Geeksforgeeks3",
"Geeksforgeeks4",
"Geeeksforgeeks5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot without overlapping labels
plot<-ggplot(sample_data, aes(name,value, fill=name)) +
geom_bar(stat = "identity") +
scale_x_discrete(guide = guide_axis(n.dodge=2))
plot
R
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geeksforgeeks1",
"Geeksforgeeks2",
"Geeksforgeeks3",
"Geeksforgeeks4",
"Geeeksforgeeks5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot without overlapping labels
plot<-ggplot(sample_data, aes(name,value, fill=name)) +
geom_bar(stat = "identity") +
scale_x_discrete(guide = guide_axis(check.overlap = TRUE))
plot
输出:
避免重叠标签
为了通过向下移动标签来避免重叠,我们使用 guide_axis()函数的 n.dodge 参数:
电阻
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geeksforgeeks1",
"Geeksforgeeks2",
"Geeksforgeeks3",
"Geeksforgeeks4",
"Geeeksforgeeks5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot without overlapping labels
plot<-ggplot(sample_data, aes(name,value, fill=name)) +
geom_bar(stat = "identity") +
scale_x_discrete(guide = guide_axis(n.dodge=2))
plot
输出:
去除重叠
要删除重叠标签,我们使用 guide_axis()函数的 check.overlap 参数:
电阻
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geeksforgeeks1",
"Geeksforgeeks2",
"Geeksforgeeks3",
"Geeksforgeeks4",
"Geeeksforgeeks5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot without overlapping labels
plot<-ggplot(sample_data, aes(name,value, fill=name)) +
geom_bar(stat = "identity") +
scale_x_discrete(guide = guide_axis(check.overlap = TRUE))
plot
输出: