ggplot2颜色设置总结

本文详细介绍了如何在R语言的ggplot2包中使用颜色来增强图表的视觉效果。从自动填充颜色到手动设置颜色,包括使用预定义的颜色方案、调色板,以及使用渐变色和自定义颜色。通过多个示例展示了如何在箱线图、散点图、地图等图形中应用颜色,从而更好地呈现数据分布和关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考

http://www.sthda.com/english/wiki/ggplot2-colors-how-to-change-colors-automatically-and-manually

http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/

查看颜色

col.set.update <- c("#c10023", "#008e17", "#fb8500", "#f60000", "#FE0092", "#bc9000","#4ffc00", "#00bcac", "#0099cc",
                    "#D35400", "#00eefd", "#cf6bd6", "#99cc00", "#aa00ff", "#ff00ff", "#00896e",
                    "#f2a287","#ffb3ff", "#800000", "#77a7b7", "#0053c8", "#00cc99", "#007CC8")
image(1:length(col.set.update),1, as.matrix(1:length(col.set.update)),col=col.set.update,xlab = "", ylab = "")

结果如下
在这里插入图片描述

prepare data

# Convert dose and cyl columns from numeric to factor variables
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
mtcars$cyl <- as.factor(mtcars$cyl)
head(ToothGrowth)

结果如下
在这里插入图片描述

head(mtcars)

在这里插入图片描述

basic plot

library(ggplot2)
# Box plot
ggplot(ToothGrowth, aes(x=dose, y=len)) +geom_boxplot()
# scatter plot
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()

结果如下
在这里插入图片描述在这里插入图片描述

颜色使用案例1

# box plot
ggplot(ToothGrowth, aes(x=dose, y=len)) +
  geom_boxplot(fill='#A4A4A4', color="darkred")
# scatter plot
ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_point(color='darkblue')

结果如下
在这里插入图片描述在这里插入图片描述

颜色使用案例2

# Box plot
bp<-ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) +
  geom_boxplot()
bp
# Scatter plot
sp<-ggplot(mtcars, aes(x=wt, y=mpg, color=cyl)) + geom_point()
sp

结果如下
在这里插入图片描述在这里插入图片描述

颜色使用案例3

# Box plot
bp + scale_fill_hue(l=40, c=35)
# Scatter plot
sp + scale_color_hue(l=40, c=35)

在这里插入图片描述在这里插入图片描述

颜色使用案例4

# Box plot
bp + scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"))
# Scatter plot
sp + scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))

结果如下
在这里插入图片描述在这里插入图片描述

颜色使用案例5

# Box plot
bp + scale_fill_manual(breaks = c("2", "1", "0.5"), 
                       values=c("red", "blue", "green"))
# Scatter plot
sp + scale_color_manual(breaks = c("8", "6", "4"),
                        values=c("red", "blue", "green"))

结果如下
在这里插入图片描述在这里插入图片描述

颜色使用案例6

library(ggplot2)
if (require("maps")) {
states <- map_data("state")
arrests <- USArrests
names(arrests) <- tolower(names(arrests))
arrests$region <- tolower(rownames(USArrests))

choro <- merge(states, arrests, sort = FALSE, by = "region")
choro <- choro[order(choro$order), ]
p=ggplot(choro, aes(long, lat)) +
  geom_polygon(aes(group = group, fill = assault)) +
  coord_map("albers",  lat0 = 45.5, lat1 = 29.5)
print(p)
}

# if (require("maps")) {
# p=ggplot(choro, aes(long, lat)) +
#   geom_polygon(aes(group = group, fill = assault / murder)) +
#   coord_map("albers",  lat0 = 45.5, lat1 = 29.5)
# }
# print(p)

在这里插入图片描述

颜色使用案例7

# Two variables
df <- read.table(header=TRUE, text='
 cond yval
    A 2
    B 2.5
    C 1.6
')

# Three variables
df2 <- read.table(header=TRUE, text='
 cond1 cond2 yval
    A      I 2
    A      J 2.5
    A      K 1.6
    B      I 2.2
    B      J 2.4
    B      K 1.2
    C      I 1.7
    C      J 2.3
    C      K 1.9
')

library(ggplot2)
# Default: dark bars
ggplot(df, aes(x=cond, y=yval)) + geom_bar(stat="identity")
# Bars with red outlines
ggplot(df, aes(x=cond, y=yval)) + geom_bar(stat="identity", colour="#FF9999") 
# Red fill, black outlines
ggplot(df, aes(x=cond, y=yval)) + geom_bar(stat="identity", fill="#FF9999", colour="black")


# Standard black lines and points
ggplot(df, aes(x=cond, y=yval)) + 
    geom_line(aes(group=1)) +     # Group all points; otherwise no line will show
    geom_point(size=3)
# Dark blue lines, red dots
ggplot(df, aes(x=cond, y=yval)) + 
    geom_line(aes(group=1), colour="#000099") +  # Blue lines
    geom_point(size=3, colour="#CC0000")         # Red dots

结果如下
在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

颜色使用案例8

# Box plot
bp + scale_fill_brewer(palette="Dark2")
# Scatter plot
sp + scale_color_brewer(palette="Dark2")

结果如下
在这里插入图片描述在这里插入图片描述

颜色使用案例9

# Install
#install.packages("wesanderson")
# Load
library(wesanderson)
# Box plot
bp+scale_fill_manual(values=wes_palette(n=3, name="Royal1"))
# Scatter plot
sp+scale_color_manual(values=wes_palette(n=3, name="Royal1"))

结果如下
在这里插入图片描述在这里插入图片描述

颜色使用案例10

# Box plot
bp + scale_fill_grey() + theme_classic()
# Scatter plot
sp + scale_color_grey() + theme_classic()

结果如下
在这里插入图片描述在这里插入图片描述

颜色使用案例11

# Box plot
bp + scale_fill_grey(start=0.8, end=0.2) + theme_classic()
# Scatter plot
sp + scale_color_grey(start=0.8, end=0.2) + theme_classic()

在这里插入图片描述在这里插入图片描述

颜色使用案例12

# Color by qsec values
sp2<-ggplot(mtcars, aes(x=wt, y=mpg, color=qsec)) + geom_point()
sp2
# Change the low and high colors
# Sequential color scheme
sp2+scale_color_gradient(low="blue", high="red")
# Diverging color scheme
mid<-mean(mtcars$qsec)
sp2+scale_color_gradient2(midpoint=mid, low="blue", mid="white",
                     high="red", space ="Lab" )

结果如下
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

颜色使用案例13

set.seed(1234)
x <- rnorm(200)
# Histogram
hp<-qplot(x =x, fill=..count.., geom="histogram") 
hp
# Sequential color scheme
hp+scale_fill_gradient(low="blue", high="red")

在这里插入图片描述在这里插入图片描述

颜色使用案例14

# Scatter plot
# Color points by the mpg variable
sp3<-ggplot(mtcars, aes(x=wt, y=mpg, color=mpg)) + geom_point()
sp3
# Gradient between n colors
sp3+scale_color_gradientn(colours = rainbow(5))

在这里插入图片描述在这里插入图片描述

颜色使用案例15

# Bars: x and fill both depend on cond2
ggplot(df, aes(x=cond, y=yval, fill=cond)) + geom_bar(stat="identity")

# Bars with other dataset; fill depends on cond2
ggplot(df2, aes(x=cond1, y=yval)) + 
    geom_bar(aes(fill=cond2),   # fill depends on cond2
             stat="identity",
             colour="black",    # Black outline for all
             position=position_dodge()) # Put bars side-by-side instead of stacked

# Lines and points; colour depends on cond2
ggplot(df2, aes(x=cond1, y=yval)) + 
    geom_line(aes(colour=cond2, group=cond2)) + # colour, group both depend on cond2
    geom_point(aes(colour=cond2),               # colour depends on cond2
               size=3)                          # larger points, different shape
## Equivalent to above; but move "colour=cond2" into the global aes() mapping
# ggplot(df2, aes(x=cond1, y=yval, colour=cond2)) + 
#    geom_line(aes(group=cond2)) +
#    geom_point(size=3)

在这里插入图片描述在这里插入图片描述在这里插入图片描述

### R语言ggplot2库中的自定义颜色设置 在R语言的`ggplot2`库中,可以通过多种方式实现图形元素的颜色定制。以下是几种常见的方法及其具体应用: #### 1. 设置全局主题颜色 通过调整`theme()`函数内的参数,可以改变整个图表的主题颜色,包括背景色、网格线以及坐标轴线条的颜色。 ```r library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() # 自定义背景和网格颜色 p + theme( panel.background = element_rect(fill = "lightblue", colour = "black"), # 背景颜色[^2] panel.grid.major = element_line(colour = "white"), # 主网格线颜色 panel.grid.minor = element_blank(), # 副网格线隐藏 axis.line.y = element_line(color = "darkred", size = 1) # Y轴线条颜色[^1] ) ``` 上述代码展示了如何修改面板背景色、主次网格线样式以及Y轴线条的颜色。 --- #### 2. 使用`scale_color_manual`或`scale_fill_manual`设定特定图层颜色 当需要为不同数据分组分配自定义颜色时,可利用`scale_color_manual`或`scale_fill_manual`来手动指定颜色映射关系。 ```r data <- data.frame( x = rep(1:5, times = 2), y = runif(10), group = factor(rep(c("A", "B"), each = 5)) ) ggplot(data, aes(x, y, color = group)) + geom_line() + scale_color_manual(values = c("A" = "forestgreen", "B" = "purple")) # 手动配色[^4] ``` 此示例说明了如何针对不同的分组变量赋予独特的显示色彩。 --- #### 3. 添加单一固定颜色到几何对象 如果仅需给某个几何对象(如折线、柱状条等)单独赋值一种固定的色调,则可以直接在其对应的绘图命令里加入`color`或者`fill`属性。 ```r df <- data.frame(x = seq(-pi, pi, length.out = 100), y = sin(seq(-pi, pi, length.out = 100))) ggplot(df, aes(x, y)) + geom_line(aes(color = NULL), color = "dodgerblue", linewidth = 1.5) + # 单一曲线颜色 labs(title="Sine Wave with Custom Line Color") ``` 这里演示的是怎样把一条正弦波形渲染成蓝色,并且设置了较粗的笔触宽度。 --- #### 总结 综上所述,在R语言下的`ggplot2`环境中,无论是整体风格还是局部细节都可以灵活地控制其呈现出来的视觉效果。这不仅限于简单的黑白灰调子,还可以引入更多鲜艳夺目的选项以增强表达力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值