R语言边学边记-ggplot作图

library(ggplot2)

#数据集

mtcars

#基本格式:ggplot(data,aes(x,y))+geom_xx()+annotate()+labs()

#aes是美化的意思,geom几何,annotate是注释,lab是标签

#散点图

ggplot(mtcars,aes(mpg,wt))+geom_point()

#线图

ggplot(mtcars,aes(mpg,wt))+geom_line()

#点线图

ggplot(mtcars,aes(mpg,wt))+geom_line()+geom_point()

#柱状图,是连续变量,变成因子

ggplot(mtcars,aes(cyl))+geom_bar()

class(mtcars$cyl)#类型

table(mtcars$cyl)#频次

#转换成因子,分类变量

ggplot(mtcars,aes(factor(cyl)))+geom_bar()

#分组,内部再分组(用am分类),形成堆积柱形图

ggplot(mtcars,aes(factor(cyl),fill=factor(am)))+geom_bar()

#百分比的堆积柱形图

ggplot(mtcars,aes(factor(cyl),fill=factor(am)))+geom_bar(position="fill")

#如果不想堆积再加,并排

ggplot(mtcars,aes(factor(cyl),fill=factor(am)))+geom_bar(position = "dodge")

#直方图,一组数据

ggplot(mtcars,aes(mpg))+geom_histogram()

#密度图

ggplot(mtcars,aes(mpg))+geom_density()

#分类,color是对点线的描绘,fill是填充

ggplot(mtcars,aes((mpg),fill=factor(vs)))+geom_density()#全是密集填充

ggplot(mtcars,aes((mpg),fill=factor(vs)))+geom_density(alpha=0.5)#透明度为0.5

ggplot(mtcars,aes((mpg),col=factor(vs)))+geom_density()#col是点线图

#箱线图(最小值,最大值,中位数,上下四分位数)

ggplot(mtcars,aes(factor(vs),mpg))+geom_boxplot()

##分组作图,qsec是连续型变量为参考指标,vs是二分变量

ggplot(mtcars,aes(wt,mpg,color=qsec))+geom_point()

ggplot(mtcars,aes(wt,mpg,color=factor(vs)))+geom_point()

#aes内与外的区别

ggplot(mtcars,aes(wt,mpg))+geom_point()

ggplot(mtcars,aes(wt,mpg))+geom_point(color="blue")

ggplot(mtcars,aes(wt,mpg,color="yellow"))+geom_point()#会将color当成一个分组变量而不是颜色


#分面作图 facet_grid()

#1.轴刻度一致

#单变量作图

ggplot(mtcars,aes(wt,mpg))+geom_point()+facet_grid(.~vs)#不能有逗号,是句号,按照横轴排列

ggplot(mtcars,aes(wt,mpg))+geom_point()+facet_grid(vs~.)#是句号,纵轴排列

#双变量作图

ggplot(mtcars,aes(wt,mpg))+geom_point()+facet_grid(am~vs)

#不同的纵轴刻度

ggplot(mtcars,aes(wt,mpg))+geom_point()+facet_grid(vs~.,scale="free")

#调整图形,大小与形状

ggplot(mtcars,aes(wt,mpg,color=factor(vs)))+geom_point(shape=3,size=3)

#文本注释#标题#添加竖横线#"加号",不能再第一行#互换XY

ggplot(mtcars,aes(wt,mpg,color=factor(vs)))+

  geom_point(shape=3,size=3)+

  annotate("text",x=4,y=20,label="yes")+

  labs(title="hello",x="sss",y="yyy")+

  geom_vline(xintercept = 3.5)+

  geom_hline(yintercept = 20)+

  coord_flip()

#调整刻度范围#替换刻度值

ggplot(mtcars,aes(wt,mpg,color=factor(vs)))+

  geom_point(shape=3,size=3)+

  annotate("text",x=4,y=20,label="yes")+

  labs(title="hello",x="sss",y="yyy")+

  geom_vline(xintercept = 4)+

  geom_hline(yintercept = 2)+

  xlim(3,8)+

  ylim(15,25)+

  scale_x_continuous(breaks=c(3,3.75),labels = c("a","b"))

你可能感兴趣的:(R语言边学边记-ggplot作图)