ggplot2--实操(图例的修改:以频数散点图为例)
2015-08-01 15:12
381 查看
ggplot2–实操(图例的修改:以频数散点图为例)
ggplot2 直接实现
画图代码:数据为两列,第二列为因子型。
> head(plotdat) SOC SOC过低报警 1 0 normal 2 2 error 3 0 normal 4 1 error 5 0 normal ###大小和高度都代表频率### g <- g + geom_point(aes(x=plotdat[,1], y=..density.., colour=plotdat[,2], shape=plotdat[,2]), stat="bin",binwidth=0.1, size=3, alpha=0.6) ##用stat转化(ggplot2 1.1有介绍),binwidth为带宽,size是点的大小,alpha是透明度 g <- g + labs(x = "Soc", y = "count", title="Soc 频数散点图") ##设定名字
问题
关于图例有三个问题:1.如何除去图例。
2.图例是双映射出来的,如何进行修改。
3.如何自己添加图例(利用图层属性)
1 除去图例
如何除去图例,利用映射属性标度,添加参数guide=”none”。2 修改图例
如单映射一样进行修改,双映射则对双映射进行修改。g <- ggplot(plotdat) g <- g + geom_point(aes(x=plotdat[,1], size=..density.., colour=plotdat[,2], shape=plotdat[,2]), stat="bin",binwidth=0.1, size=3, alpha=0.6) g <- g + labs(x = "Soc", y = "count", title="Soc 频数散点图") g <- g + scale_colour_hue(name="SOC过低报警") g <- g + scale_shape_manual(values=c(17,19), name="SOC过低报警") g
3 自己添加图例
由途中可以看到直接利用ggplot2进行画频数散点图,底部会将带宽画出来。为解决这个问题将对数据进行处理。下列代码中注意colour的位置,在mapping内时会产生图例。plot_normal <- plotdat[which(plotdat[,2]=="normal"),] plot_error <- plotdat[which(plotdat[,2]=="error"),] plot_nor <- as.data.frame(table(plot_normal[,i])) plot_err <- as.data.frame(table(plot_error[,i])) plot_nor[,1] <- as.numeric(plot_nor[,1]) plot_err[,1] <- as.numeric(plot_err[,1]) g <- ggplot() g <- g + geom_point(aes(x=plot_nor[,1], y=plot_nor[,2], colour="blue"), size=3, data=plot_nor, alpha = 0.6) g <- g + geom_point(aes(x=plot_err[,1], y=plot_err[,2], colour="red"), size=3, data=plot_err, alpha = 0.6) g <- g + labs(x = names(plotdat)[i], y = "count", title="Soc 频数散点图") g <- g + scale_colour_hue( name = "SOC过低报警", labels = c("normal", "error")) print(g)