自定义ggplot2图的图例。这里我们要修改非数据组件,通常通过theme()命令来完成。 此页面受到ggplot2(?theme)帮助页面的强烈启发。 另外,请访问非常强大的ggplot2文档以获取更多信息。我们从mtcars数据集和默认图例开始:
library(ggplot2)
basic=ggplot(mtcars, aes(wt, mpg, colour = factor(cyl), shape = factor(vs) )) +
geom_point()
basicimage.png
basic+labs(
colour = "name1",
shape = "name2"
)image.png
basic + guides(shape=FALSE)image.png
要删除图例,请在theme()中使用legend.position =“none”。 要更改其位置,但在图表外使用bottom,left,right或top。 或者使用0和1之间的相对坐标放置在图中。
#1: no legend
basic + theme(legend.position = "none")#2: around the plot
basic + theme(legend.position = "bottom")#3: inside the plot
basic + theme(
legend.position = c(.95, .95),
legend.justification = c("right", "top"),
legend.box.just = "right",
legend.margin = margin(6, 6, 6, 6)
)# 图例被红框包裹
basic + theme(
legend.box.background = element_rect(color="red", size=2),
legend.box.margin = margin(116, 6, 6, 6)
)# 图例中指示图标的边框设置
basic + theme(legend.key = element_rect(fill = "white", colour = "black"))#图例中的字体设置
basic + theme(legend.text = element_text(size = 8, colour = "red"))# 设置图例中的标题
basic + theme(legend.title = element_text(face = "bold"))