如何在 R 中的 ggplot2 中手动指定条形图的颜色?
在本文中,我们将讨论如何在 R 编程语言中为 ggplot2 中的 Barplot 手动指定颜色。
要在 ggplot2 中的 Barplot 中指定条形图的颜色,我们使用 ggplot2 包的scale_fill_manual函数。在这个函数中,我们需要为每个条形指定一种颜色作为向量。我们可以使用名称和十六进制代码来使用颜色。
Syntax: plot+ scale_fill_manual(values=
示例 1:
这是一个带有默认颜色的基本 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))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot with default colors
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("Geek1","Geek2",
"Geek3","Geek4",
"Geeek5") ,
value = c(31,12,15,28,45))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot with default colors
plot<-ggplot(sample_data,
aes(name,value, fill=name))
+ geom_bar(stat = "identity")
# add scale_fill_manual function to specify colors
plot + scale_fill_manual(values = c("green","yellow",
"red","pink","blue"))
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 default colors
plot<-ggplot(sample_data, aes(name,value, fill=name)) +
geom_bar(stat = "identity")
# add scale_fill_manual function to specify colors
plot + scale_fill_manual(values = c("#207345","#0d576e",
"#610d6e","#6e0d27",
"#6e470d"))
输出:
要手动指定颜色,只需添加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))
# Load ggplot2 pckage
library("ggplot2")
# Create bar plot with default colors
plot<-ggplot(sample_data,
aes(name,value, fill=name))
+ geom_bar(stat = "identity")
# add scale_fill_manual function to specify colors
plot + scale_fill_manual(values = c("green","yellow",
"red","pink","blue"))
输出:
我们甚至可以使用颜色的十六进制代码代替名称:
电阻
# 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 default colors
plot<-ggplot(sample_data, aes(name,value, fill=name)) +
geom_bar(stat = "identity")
# add scale_fill_manual function to specify colors
plot + scale_fill_manual(values = c("#207345","#0d576e",
"#610d6e","#6e0d27",
"#6e470d"))
输出: