当前位置: 代码迷 >> 综合 >> R语言绘制图形
  详细解决方案

R语言绘制图形

热度:46   发布时间:2024-02-20 17:49:30.0
#3.1  常用图形参数
#3.1.1颜色
#对  swiss  mtcars  esoph 绘制散点图
head(swiss)   #查看数据集前几行
head(mtcars)
head(esoph)
head(women)
plot(swiss,col="pink")  #颜色名称
plot(swiss,col=554)  # 颜色下标
plot(swiss,col="#FF0000")  #十六进制的颜色值mycolor <- rgb(red=0,green = 50,blue=100,max=255)
plot(swiss,col=mycolor)  #通过RGB的值#对其他图形参数颜色进行设置
plot(swiss,main=" 散点图",sub="数据来源,swiss数据集",col="yellow",col.main="blue",col.sub="green",col.axis="grey",col.lab="red")
colorsplot(women,main=" 散点图",sub="数据来源,women数据集",col="yellow",col.main="peru",col.sub="navy",col.axis="grey",col.lab="purple")#主题颜色
#par(mfrow=c(3,2))
barplot(rep(1,7),col=rainbow(7),main="col=rainbow(7)")
barplot(rep(1,7),col=heat.colors(7),main="col=heat.color(7)")
barplot(rep(1,7),col=terrain.colors(7),main="col=terrain.color(7)")
barplot(rep(1,7),col=topo.colors(7),main="col=topo.colors(7)")
barplot(rep(1,7),col=cm.colors(7),main="col=rainbow(7)")#3.1.2 文字元素
#字体
plot(0:4,type="n",axes=F,xlab = NA,ylab = NA)  #无x,y轴
plot(0:4,type="n",axes=T,xlab = "x",ylab = "y")  #有xy 轴type <- c("正常字体","粗体字体","斜体字体","粗斜体字体")
for (i in 1:4){text(2,5-i,labels = paste0("font=",i,":",type[i]),font=i)
}#大小
plot(0:5,type = "n",axes=F,xlab = NA,ylab = NA)text(2,5,labels="cex=0.5:放大0.5倍",cex=0.5)
text(2,4,labels="cex=0.8:放大0.8倍",cex=0.8)
text(2,3,labels="cex=1:放大1倍:正常大小",cex=1)
text(2,2,labels="cex=1.5:放大1.5倍",cex=1.5)
text(2,1,labels="cex=2:放大2倍",cex=2)#练习  改为循环语句实现
cex <- c(0.5,0.8,1,1.5,2)
num <- 1:5
for (i in cex){for(j in num){text(2,j,labels = "cex=0.5:放大0.5倍",cex=cex[i])}
}#3.1.3  点元素
plot(1,col="white",xlim=c(1,7),ylim=c(1,5),main="点样式 pch=",xlab=NA,ylab=NA)for(i in c(0:25)){x<-(i%%5)*1+1y<-6-(i%%5)-1if(i>21){points(x,y,pch=i,col="red",bg="yellow",cex=2)}else{points(x,y,pch=i,cex=2)}text(x+0.2,y,labels = i)
}#3.1.4 线元素
plot(x=1:10,y=rep(1,10),type="1",ylim=c(1,8),xlim=c(-1,10),axes = T,xlab=NA,ylab=NA)
text(0,1,labels = "lty=0")
for(i in 2:7){lines(x=1:10,y=rep(i,10),lty=i-1,xlab=NA,ylab=NA)text(0,i,labels = paste0("lty=",i-1))
}##3.2低级绘图函数
#3.2.1标题
#箱线图百度百科
str(PlantGrowth)
attach (PlantGrowth)
head(PlantGrowth)
boxplot(weight~group,col=heat.colors(3),main=list ( "weight按照group分类的箱线图",font=4 ,col="red" , cex=1.5),sub=list("数据来源:PlantGrowth数据集", font=3,col="green" , cex=0.8),zlab="group" ,ylab="weight")
#title函数
boxplot(weight~group,col=heat.colors(3))
title(main=list("weight按照group分类的箱线图",font=4 ,col="red",cex=1.5),sub=list("数据来源:PlantGrowth数据集",font=3,col="green" , cex=0.8),xlab="group" , ylab="weight")#title另一种方式
boxplot(weight~group, col=heat.colors(3))
title (main="weight按照group分类的箱线图",font.main=4 ,col.main="red" , cex.main=1.5,sub="数据来源:PlantGrowth数据集",font.sub=3,col.sub="green" , cex.sub=0.8,xlab="group" , ylab="weight")#3.2.2坐标轴
#加载iris数据到内存
attach(PlantGrowth)
head(PlantGrowth)
#绘制箱线图
boxplot(weight~group,col=heat.colors(3),axes=FALSE,xlab="group",ylab="weight")
#设置x轴样式
axis(side=1,at=1:3,labels=unique (group), col.axis="red",tick=FALSE)
#设置Y轴样式
axis(side=2,col.ticks = "gold",font = 3, col = "blue")
#3.2.3图例
#绘制分组柱状图
head(trees)
barplot(as.matrix(trees),beside=TRUE,col=cm.colors(6))
#练习:使用自己的数据画图
#添加图例
legend ( "top" , legend=rownames(as.matrix(trees)),ncol=5,fill=cm.colors (5),bty="n")
?legend
#3.2.4网格线
op <- par(mfcol=1:2)
barplot(as.matrix(trees),beside = TRUE,col=cm.colors(5),main="plot trees with grid()")
grid()
barplot(as.matrix(trees),beside = TRUE,col=cm.colors(5),main="plot trees with grid(NA,7,lty=2,lwd=1.5,col='green')")
grid(NA,7,lty=2,lwd=1.5,col="green")
par(mfcol=c(1,1))#3.2.5点
set.seed (1234)
data <- c(rnorm (100,mean=0, sd=1),rnorm (3,mean=4, sd=1))
head(data)
length (data)
str(data)
summary(data)
boxplot(data,col="violet", ylim=c(-4,5),outline=F)
points(rep(1,4),data[99:102],pch=21,bg=c("pink","red","blue","black"), cex=1.2)
data [101 :103]
#3.2.6文字
text (rep(1,4) ,data[99:102],pos=4,label=paste0("异常值" , round (data[99:102],4)))
#3.2.7线
#lines函数
install.packages ( "ggplot2")
data (trees, package = "ggplot2")
attach (trees)
#将economics加载到内存
str(trees)
head(trees)
? ?economics
?ggplot2::PlantGrowth
plot(Height,Girth,type="l",ylab="", ylim=c(0,100))#绘制psavert随时间变化的时序图
lines(Height,Volume,type="l",col="blue")#绘制uempmed曲线,并设置为蓝色
detach(economics)
#将economics从内存中移除
#abline函数
#通常会调用abline画一条线
attach (trees)
#绘制一幅简单的散点图
plot (Girth~Height)
#绘制Petal.Length变量均值的水平线
abline (h=mean (Girth) ,col="gray60")
#绘制Petal.width变量均值的竖直线
abline (v=mean (Height) , col="gray60")
#绘制拟合直线
abline (lm(Girth~Height) ,col="red" ,lwd=2,lty=3)
detach()
##3.3 高级绘图函数
#3.3.1散点图
#1.普通散点图
par (mfrow=c (1,2))
#绘制—维数据
plot(x=rnorm (20))
#绘制二维数据
plot(PlantGrowth)
par(mfrow=c (1,1))
#2.散点图矩阵
#利用plot函数
plot(trees[,1: 3],main="利用plot函数绘制散点图矩阵")
#利用pairs函数
#方法一
pairs (trees[,1:3],main="利用pairs函数绘制散点图矩阵")
#方法二
pairs (~Girth+Height+Volume,data=trees,main="利用pairs函数绘制散点图矩阵")
#3.高密度散点冬
#创建—个太数据集
n <-100000
x1<- matrix(rnorm(n), ncol = 2)
head (x1)
x2<- matrix(rnorm(n,mean = 10, sd = 6), ncol = 2) 
x <- rbind (x1,x2)
#利用plot与smoothscatter函数绘制散点图par(mfrow=c(1,2))
plot (x, main="利用plot函数绘制普通散点图")
smoothScatter(x,main="利用smoothscatter函数绘制高密度散点图")
par(mfrow=c(1,1))#3.3.2气泡图
str(PlantGrowth)
data ( "trees" ,package = "ggplot2")
#随机抽取500个样本
diamonds1 <- diamonds[sample(1:nrow(trees),500),]
head(diamonds)
attach(diamonds1)
#计算钻石体积
volumn<-x*y*z
#把钻石体积进行归一化处理,并赋予对象size
size<-(volumn-min (volumn))/(max(volumn)-min (volumn) )
#利用plot函数绘制气泡图
plot(carat,price, cex=size*2)
#利用symbols函数绘制气泡图
x<-rnorm( 5);x
y<-rnorm( 5);y
r<-abs ( rnorm (5));r
symbols (x,y, circle = r,inches =F,bg=rainbow ( 5))
? symbols#画员
plot(1:5,1:5,type = "n",xlim = c(0,6),ylim = c(0,6))
symbols(x = 1:5,y = 1:5,circles = rep(1,5),inches = FALSE,add = TRUE)
#画方框
plot(1:5,1:5, type = "n", xlim = c(0,6), ylim = c(0,6))
symbols(x = 1:5,y = 1:5,squares = rep(2,5),inches = FALSE,add = TRUE)
#画长方形
plot(1:5,1:5, type = "n",xlim = c(0,6), ylim = c(0,6))
#symbols(x = c(1,4),y = c(3,4),rectangles = matrix(c(2,3,3,2),byrow = T,nrow = 2)
#3.3.3线图
type <- c ( 'l','b','c', 'o', 's', 'S')
par(mfrow=c (2,3))
for (i in 1:6){plot(1:10,type=type[i] ,main=paste ( "type=",type[i]))
}
par (mfrow=c(1,1))
#3.3.4柱状图
par(mfrow=c(1,2))
for(i in c (FALSE,TRUE)){barplot(as.matrix(trees), horiz = i,beside = T, col = rainbow(3))
}
par(mfrow=c(1,1))
#增加图例
barplot(as.matrix(trees),beside = T,col = rainbow(3),legend.text =rownames (as.matrix(trees)) )#3.3.5饼图
head(trees)
pie(table(trees$Girth) )
#3.3.6直方图和密度图
#绘制直方图
data(economics, package = "ggplot2")
#将economics加载到内存
attach (trees)
par(mfrow=c(2,2))
hist(Girth,8,xlab="", ylab="频数", col="blue",main="干围对植物产量的影响")
hist(Height,30,xlab="高度", ylab="频数", col="blue",main="高度对植物产量的影响")
hist(Volume,8,xlab="体积", ylab="频数", col="green",main="体积对植物产量的影响")
hist(Height,30,xlab="高度", ylab="频数", col="green",main="一周内平均失业持续时间(较多区间)")
par(mfrow=c(1,1))
#将economics从内存中释放
detach (economics)
#3.3.9茎叶图
str (mtcars)
?mtcars
stem(mtcars$wt)
#高级绘图工具包
###ggplot2包绘图工具
#利用ggplot函数绘制箱线图
head(PlantGrowth)
library (ggplot2)
ggplot(PlantGrowth,aes(x=group,y=weight,fill=group))+geom_boxplot()+labs(title="依据处理方式分组的植物产量箱线图")
#利用ggplot函数绘制小提琴图
ggplot(PlantGrowth,aes(x=group,y=weight,fill=group))+geom_violin() +geom_jitter()+labs(title="依据处理方式分组的植物产量箱线图")
#利用ggplot的分面函数绘制分面板密度图
install.packaqes ("strinqr")
head(singer)
data(PlantGrowth, package = "lattice")
ggplot (data=PlantGrowth,aes (x=weight, fill=group))+geom_density()+facet_grid(group~.)
ggplot(data=singer,aes (x=weight, fill=group))+geom_density() +facet_wrap(group~,ncol=4)+theme (legend.position="none")
#调整图形填充颜色
install.packages ("qridExtra")
library(qridExtra)
#方式一:使用scalecolormanual函数
head(Formaldehyde)
head(trees)
g1 <- ggplot (trees,aes (x=Girth, y=Volume,colour=Height,shape=group))+  scale_color_manual(values=c("orange","olivedrab", "navy")) +geom_point(size=3)
#方式而:使用scalecolorbrewer函数
g2 <- ggplot(trees,aes(x=Girth, y=Volume,colour=Height, shape=group)) +  scale_color_brewer(palette="Set1")+geom_point (size=3)
grid.arrange(gl,g2,ncol=2)
#保存ggplot的图形
ggplot(trees,aes (x=Girth, y=Volume,colour=Height))+geom_point(size=2)
ggsave (file="mygraph.pdf",width=5,height=4)#ggthemes包
library(ggplot2)
#install.packages("ggthemes")
library (ggthemes)
head(mtcars)
str(mtcars)
library(gridExtra)
p1<- ggplot (trees, aes(x=Girth,y=Volume))+geom_point(size=3)
# Economist themes
p2<-p1 + ggtitle("Economist theme") +theme_economist() + scale_colour_economist ()
# Solarized theme 
p3 <- pl + ggtitle("Solarized theme") +theme_solarized() + scale_colour_solarized("blue")
grid.arrange(p2,p3,ncol=2)# Stata theme
p4<- p1 + ggtitle("Stata them") +theme_stata()+ scale_colour_stata()
# Excel 2003 theme 
p5<-p1 + ggtitle("Excel 2003 them")+theme_excel() + scale_colour_excel()
grid.arrange (p4,p5,ncol = 2)
#rbokeh包
#绘制散点图
library(dplyr)
if(!require(rbokeh))install.packages ("rbokeh")
library(dplyr)
library(rbokeh)
head(cars)
Z <-lm(optden ~ carb, data = Formaldehyde)
P <- figure(width = 600, height = 600) %>%ly_points(Formaldehyde,hover = Formaldehyde) %>%ly_lines(lowess(Formaldehyde), legend = "lowess") %>%ly_abline(Z, type = 2, legend = "lm")
P                  
#绘制直方图
head(faithful)
h <- figure(width = 600, height = 400) %>%ly_hist(carb,data =Formaldehyde, breaks = 40,freq = FALSE) %>%ly_density(carb, data = Formaldehyde)
h
#绘制箱线图
head(lattice::singer)
figure(ylab = "Height (inches)", width = 600)%>%ly_boxplot (group, weight, data = PlantGrowth)#plotly包
revenue <-read.csv("revenue.csv", encoding = "UTF-8")
revenue 
#绘制柱状图
if(!require(plotly))install.packages ("plotly")
library(plotly)
p <- plot_ly(revenue,Y = ~week,x = ~game_name, type = "bar",name = "本周")
p              
p %>% add_trace(y = ~last_week,name = "上周")
p%>%add_trace(y= ~上周,name="上周")
layout (barmode = 'stack',xazis = list(title =""), vaxis = list(title =""), title="游戏收入数据")# leaflet@
#在地图上标记R语言的诞生地--新西兰奥克兰大学
install.packages("leaflet")
library(leaflet)
leaflet()%>%addTiles() %>% addMarkers (lng=174.768,lat=-36.852, popup="ThebirthplaceofR")
# dygraphs@
if(!require(dygraphs))  install.packages("dygraphs")
#LTV预测曲线
library(dygraphs)
LTV <- read.csv("LTV.csv")
LTV.ts<- ts(LTV)
dygraph(LTV.ts,main="LTV forecast")%>%dySeries("V1",label="LTV", strokeWidth = 2)%>%dyOptions(colors = "black", fillGraph = FALSE,fillAlpha = 0.4)%>%dyHighlight(highlightCircleSize = 5,highlightSeriesBackgroundAlpha = 0.2,hideOnMouseOut = FALSE)%>%dyAxis("x", drawGrid = FALSE) %>%dyAxis("y", label = "LTV(Life Time Value) ")%>%dyRangeSelector()#DT包
install.packages("DT")
library(DT)
datatable(trees)
datatable(trees, rownames = FALSE)#不输出行号#networkD3包
#利用simpleNetwork函数绘制简单网络图
install.packages ("networkD3")
library (networkD3)
src <- c("A","A","A","A","B","B", "C","C","D")
target <- C("B", "C",  "D","J","E", "F", "G", "H","I")
networkData <- data.frame(src, target)
simpleNetwork(networkData, zoom-T)
#利用networkD3函数绘制力导向网络图
#加载数据
data (MisLinks)
data (MisNodes)
#画图
forceNetwork (Links = MisLinks, Nodes = MisNodes,Source = "source", Target = "target",Value = "value", NodeID = "name",Group = "group", opacity = 0.8)#pairsD3包
if(!require (pairsD3)) install.packages("pairsD3")
library(pairD3)
pairsD3(iris[,1:4],grou = iris[,5],labels=c("花萼长度","花萼宽度","花瓣长度","花瓣宽度","种类"))# scatterD3@
if(!require(scatterD3)) install.packages("scatterD3")
mtcars$names <- rownames (mtcars)
scatterD3 (data = mtcars,x=wt,y=mpg,lab = names,col_var = cyl, symbol_var = am,xlab = "Weight", ylab = "Mpg", col_lab = "Cylinders",symbol_lab = "Manual transmission")#timevis包
if(!require(timevis))  install.packages("timevis")
data <- data.frame(id =1:4,content=c("事项一","事项二","事项三","事项四"),start= c("2016-11-10","2016-11-11", "2016-11-20","2016-12-14 15:00:00"),end= C(NA,NA, "2016-12-04", NA)
) 
timevis(data)#rpivotTable包
devtools::install_github (c ("ramnathv/htmlwidgets",  "smartinsightsfromdata/rpivotTable"))
library(rpivotTable)
mtcarsSvs <-factor(ifelse(mtcarsSvs==0,"自动","手动"))
colnames (mtcars) [8]<-"传输"
rpivotTable (mtcars)

 

  相关解决方案