=======================
自定义ggplot2图的图例。这里我们要修改非数据组件,通常通过theme()
命令来完成。 此页面受到ggplot2(?theme)
帮助页面的强烈启发。 另外,请访问非常强大的ggplot2文档以获取更多信息。我们从mtcars数据集和默认图例开始:
library(ggplot2)basic=ggplot(mtcars, aes(wt, mpg, colour = factor(cyl), shape = factor(vs) )) + geom_point()basic
修改图例中的分类名字
basic+labs( colour = "name1", shape = "name2")
删除图例中的一类
basic + guides(shape=FALSE)
要删除图例,请在theme()
中使用legend.position =“none”
。 要更改其位置,但在图表外使用bottom,left,right或top。 或者使用0和1之间的相对坐标放置在图中。
#1: no legendbasic + theme(legend.position = "none")
#2: around the plotbasic + theme(legend.position = "bottom")
#3: inside the plotbasic + 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"))
联系客服