📜  在 R 中使用 ggplot2 着色条形图

📅  最后修改于: 2022-05-13 01:54:52.157000             🧑  作者: Mango

在 R 中使用 ggplot2 着色条形图

在本文中,我们将讨论如何使用 R 编程语言中的 ggplot2 包为条形图着色。

方法一:在 aes函数中使用 fill 参数

在 aes函数中使用 fill 参数等于给定数据的分组变量。美学映射描述了数据中的变量如何映射到几何图形的视觉属性(美学)。美学映射可以在 ggplot() 和单独的层中设置

句法:

aes(x, y, ...)

参数:

x, y, ... :name-value 对列表,形式为审美 = 变量,描述层数据中的哪些变量应映射到配对的 geom/stat 使用的美学。

例子:

我们将为条形图使用 6 个不同的数据点,然后借助 aes函数中的填充参数,我们将在 R 编程语言中将默认颜色应用于条形图。

R
# load the library
library("ggplot2")
  
# create the dataframe with letters and numbers
gfg < -data.frame(
    x=c('A', 'B', 'C', 'D', 'E', 'F'),
    y=c(4, 6, 2, 9, 7, 3))
  
# display the bar
ggplot(gfg, aes(x, y, fill=x)) + geom_bar(stat="identity")


R
# load the package
library("ggplot2")
  
# create a dataframe
# with letters and numbers
gfg < -data.frame(
    x=c('A', 'B', 'C', 'D', 'E', 'F'),
    y=c(4, 6, 2, 9, 7, 3))
  
# display bar
ggplot(gfg, aes(x, y, fill=x)) +
geom_bar(stat="identity") +
scale_fill_manual(values=c("A"="purple",
                           "B"="yellow",
                           "C"="red",
                           "D"="blue",
                           "E"="green",
                           "F"="black"))


输出:-

方法二:使用 scale_fill_manual函数

scale_fill_manual() 允许您指定自己的一组从数据级别到美学值的映射。

句法:

scale_fill_manual(..., values)

参数:

…:常见的离散比例参数:名称、中断、标签、na.value、限制和指南。

例子:

我们将为条形图使用 6 个不同的数据点,然后在使用 scale_fill_manual函数的帮助下,我们将在 R 编程语言中将给定的颜色应用于条形图。

输入:

R

# load the package
library("ggplot2")
  
# create a dataframe
# with letters and numbers
gfg < -data.frame(
    x=c('A', 'B', 'C', 'D', 'E', 'F'),
    y=c(4, 6, 2, 9, 7, 3))
  
# display bar
ggplot(gfg, aes(x, y, fill=x)) +
geom_bar(stat="identity") +
scale_fill_manual(values=c("A"="purple",
                           "B"="yellow",
                           "C"="red",
                           "D"="blue",
                           "E"="green",
                           "F"="black"))

输出:-