library(ggplot2)
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
Use guides(fill=FALSE), replacing fill with the desired aesthetic. 使用 guides(fill=FALSE) 移除由ase中 匹配的fill生成的图例, 也可以使用theme You can also remove all the legends in a graph, using theme.
bp + guides(fill=FALSE)
# 也可以这也
bp + scale_fill_discrete(guide=FALSE)
# 移除所有图例
bp + theme(legend.position="none")
修改图例的内容
改变图例的顺序为 trt1, ctrl, trt2:
bp + scale_fill_discrete(breaks=c("trt1","ctrl","trt2"))
If you use both colour and shape, they both need to be given scale specifications. Otherwise there will be two two separate legends. 如果同时使用 color和shape,那么必须都进行scale_xx_xxx的定义,否则color和shape的图例就会合并到一起, 如果 scale_xx_xxx 中的name相同,那么他们也会合并到一起.
yyy 的分离 hue: 设置色调范围(h)、饱和度(c)和亮度(l)获取颜色 manual: 手动设置 gradient: 颜色梯度 grey: 设置灰度值discrete: 离散数据 (e.g., colors, point shapes, line types, point sizes) continuous 连续行数据 (e.g., alpha, colors, point sizes)
修改data.frame的factor
pg <- PlantGrowth # Copy data into new data frame
# Rename the column and the values in the factor
levels(pg$group)[levels(pg$group)=="ctrl"] <- "Control"
levels(pg$group)[levels(pg$group)=="trt1"] <- "Treatment 1"
levels(pg$group)[levels(pg$group)=="trt2"] <- "Treatment 2"
names(pg)[names(pg)=="group"] <- "Experimental Condition"
# View a few rows from the end product
head(pg)
## weight Experimental Condition
## 1 4.17 Control
## 2 5.58 Control
## 3 5.18 Control
## 4 6.11 Control
## 5 4.50 Control
## 6 4.61 Control
# Make the plot
ggplot(data=pg, aes(x=`Experimental Condition`, y=weight, fill=`Experimental Condition`)) +
geom_boxplot()
修改标题和标签的显示
bp + theme(legend.title = element_text(colour="blue", size=16, face="bold"))
bp + theme(legend.text = element_text(colour="blue", size = 16, face = "bold"))
修改图例的框架
bp + theme(legend.background = element_rect())
bp + theme(legend.background = element_rect(fill="gray90", size=.5, linetype="dotted"))
设置图例的位置
图例的位置(left/right/top/bottom):
bp + theme(legend.position="top")
也可以根据坐标来设置图例的位置, 左下角为 (0,0), 右上角为(1,1)
# Position legend in graph, where x,y is 0,0 (bottom left) to 1,1 (top right)
bp + theme(legend.position=c(.5, .5))
# Set the "anchoring point" of the legend (bottom-left is 0,0; top-right is 1,1)
# Put bottom-left corner of legend box in bottom-left corner of graph
bp + theme(legend.justification=c(0,0), # 这个参数设置很关键
legend.position=c(0,0))
# Put bottom-right corner of legend box in bottom-right corner of graph
bp + theme(legend.justification=c(1,0), legend.position=c(1,0))
# No outline
ggplot(data=PlantGrowth, aes(x=group, fill=group)) +
geom_bar()