R语言中plot()函数的基本格式如下:
plot(x,y,...)
plot函数中,x和y分别表示所绘图形的横坐标和纵坐标;函数中的...为附加的参数。
plot函数默认的使用格式如下:
plot(x, y = NULL, type = "p", xlim = NULL, ylim = NULL, log = "", main = NULL, sub = NULL, xlab = NULL, ylab = NULL, ann = par("ann"), axes = TRUE, frame.plot = axes, panel.first = NULL, panel.last = NULL, asp = NA, ...)
主要参数的含义如下:
(1)type为一个字符的字符串,用于给定绘图的类型,可选的值如下:
"p":绘点(默认值);
"l":绘制线;
"b":同时绘制点和线;
"c":仅绘制参数"b"所示的线;
"o":同时绘制点和线,且线穿过点;
"h":绘制出点到横坐标轴的垂直线;
"s":绘制出阶梯图(先横后纵);
"S":绘制出阶梯图(先纵后竖);
"n":作空图。
(2)main参数 字符串,给出图形的标题;
(3)sub参数 字符串,给出图形的子标题;
(4)xlab 和 ylab参数 字符串,用于给出x轴和y轴的标签。
(5)xlim 和 ylim参数 都是二维向量,分别表示x轴和y轴的取值范围。
x <- runif(50,0,2)
y <- runif(50,0,2)
plot(x, y, main="我的第一个散点图", sub="subtitle",
xlab="横坐标", ylab="纵坐标", pch=16)
text(0.6,0.6,"(0.6,0.6)")
abline(h=.6,v=.6, col='red')
x <- runif(50,0,2)
y <- runif(50,0,2)
plot(x, y, type="n", xlab="", ylab="", axes=F)
points(x,y) #添加坐标点
axis(1) #添加横轴
axis(at=seq(0,2,0.5), side=2) #添加纵轴
box() #补齐散点图的边框
title(main="散点图", sub="subtitle", xlab="x轴", ylab="y轴")
abline(h=0.6,v=0.6,col="red")
利用ggplot2绘图,请记住下面这个格式,因为这个格式ggplot2绘制其他图形都是这一格式。
ggplot(data, aes(x, y)) + geom_point()
aes中的x,y值分别表示在x,y轴的变量;geom_point表示增加散点图图层。
散点图分组有两种方式,一种利用shape,以点的形状来区分各种;一种用color,以点的颜色来区分.但是得记住,分组的变量必须为因子变量或者字符串。
ggplot(data, aes(x, y, colour)) + geom_point()#设置colour参数以颜色区分
ggplot(data, aes(x, y, shape)) + geom_point()#设置shape参数以形状区分
library(ggplot2)
#read in data
data = read.table("scatter_plot-3.txt", header=T, sep="\t")
ggplot(data[1:10,], aes(x=carat,y=price)) + geom_point()
##draw all the points
ggplot(data, aes(x=carat,y=price)) + geom_point()
#there are too much points so that some of them are overplotted
#there are different methods to highlight the overploting points
#当点的密度大时,我们可以改变点的透明度来区分各个点。
# 当然我们可以使用bin的方法来区分,这种方法是把点的形状设定为长方形,密度越大的长方形区域越透明。
ggplot(data, aes(x=carat,y=price)) +
geom_point(alpha=0.05)
#另一种方法是把点切到不同的箱子里.
ggplot(data, aes(x=carat,y=price)) + stat_bin2d()
ggplot(data, aes(x=carat,y=price)) +
stat_bin2d(bins=50) +
scale_fill_gradient(low="lightblue", high="red" ,limits=c(0,5000))
#show the bins in hexagon using package hexbin
library(hexbin)
ggplot(data, aes(x=carat,y=price)) + stat_binhex() +
scale_fill_gradient(low="lightblue", high="red",
breaks=c(0, 250, 500, 1000, 2000, 4000, 6000),
limits=c(0,6000))
本文分享自 MedBioInfoCloud 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体分享计划 ,欢迎热爱写作的你一起参与!