如何在 R 中的 Barplot 中突出显示一个条?
在本文中,我们将讨论如何在 R 编程语言中突出显示条形图中的条形。
首先,让我们使用 ggplot2 创建一个没有突出显示的条形图的基本条形图。
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),
highlight= c(0,0,1,0,0) )
# 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),
highlight= c(0,0,1,0,0) )
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot
plot<-ggplot(sample_data,
aes(name, value, fill=highlight)) +
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),
highlight= c("0","0","1","0","0") )
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot with highlighted bar
plot<-ggplot(sample_data,
aes(name,value,fill=highlight)) +
geom_bar(stat = "identity")+
scale_fill_manual( values = c( "1"="green", "0"="darkgray" ),
guide = FALSE )
plot
输出:
在条形图中突出显示条
为了在条形图中创建自动颜色,我们使用 ggplot2 图的 fill 属性。除了需要突出显示的条之外,我们对所有条使用具有相同值的向量。
电阻
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geek1","Geek2",
"Geek3","Geek4",
"Geeek5") ,
value = c(31,12,15,28,45),
highlight= c(0,0,1,0,0) )
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot
plot<-ggplot(sample_data,
aes(name, value, fill=highlight)) +
geom_bar(stat = "identity")
plot
输出:
突出显示条形图中的特定条
为了在条形图中创建手动颜色,我们使用 ggplot2 图的 fill 属性和 scale_fill_manual()函数。除了需要突出显示的条之外,我们对所有条使用具有相同值的向量,然后我们为每个值定义一种颜色,以便根据指定给它的值对每个条进行着色:
电阻
# Create sample data
set.seed(5642)
sample_data <- data.frame(name = c("Geek1","Geek2",
"Geek3","Geek4",
"Geeek5") ,
value = c(31,12,15,28,45),
highlight= c("0","0","1","0","0") )
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot with highlighted bar
plot<-ggplot(sample_data,
aes(name,value,fill=highlight)) +
geom_bar(stat = "identity")+
scale_fill_manual( values = c( "1"="green", "0"="darkgray" ),
guide = FALSE )
plot
输出: