r语言绘图技巧(昨晚熬夜整理的超级R绘图技巧)
# 加载需要的包
library(tidyverse)
library(gcookbook)
ggplot(heightweight,aes(ageYear,heightIn,shape=sex)) geom_point() scale_shape_manual(values = c(1,2)) ggsave("1.jpg")
2.scale_fill_gradient设置legend的颜色
ggplot(heightweight,aes(weightLb,heightIn,fill=ageYear)) geom_point(shape=21,size=3) scale_fill_gradient(low="black",high="red")
3.Alpha参数修改透明度
ggplot(diamonds,aes(carat,price)) geom_point(alpha=.1)
4.bin设置区分度,scale_fill_gradient limit设置上下标
sp <- ggplot(diamonds,aes(carat,price)) sp stat_bin2d(bins = 50) scale_fill_gradient(low="lightblue",high="red",limits=c(0,6000))
5.stat_smooth(method=lm)对散点图增加线性回归
sp1 <- ggplot(heightweight,aes(ageYear,heightIn)) geom_point() sp1 stat_smooth(method = lm)
6.Annotate添加文本
sp1 annotate("text",label="r^2=0.42",x=16,y=52)
7.geom_text(aes(label=))批量添加标签
sp1 geom_text(aes(label=sex),size=3)
8.geom_text通过设置x=确定确定标签位置
sp1 geom_text(aes(ageYear 0.2,label=sex,size=2))
9.stat_density2d()画二维散点图
sp2 <-ggplot(faithful,aes(eruptions,waiting)) geom_point() stat_density2d()
10.position图形的位置关系,相邻的两个柱子是分开还是重叠在一起
ggplot(cabbage_exp,aes(Date,Weight,fill=Cultivar)) geom_bar(stat = "identity",position ="dodge")
11.width调整柱形图的宽度
ggplot(cabbage_exp,aes(Date,Weight,fill=Cultivar)) geom_bar(stat = "identity",width=.5)
12.position=position_dodge(0.7)
ggplot(cabbage_exp,aes(Date,Weight,fill=Cultivar)) geom_bar(stat = "identity",position=position_dodge(0.7),width = .65)
13.coord_polar()柱形图升级台风图
ggplot(wind,aes(DirCat,fill=SpeedCat)) geom_histogram(binwidth = 15,boundary=-7.5) coord_polar() scale_x_continuous(limits = c(0,360))
14.坐标轴的位置设置
sp1 <- ggplot(heightweight,aes(ageYear,heightIn)) geom_point() sp1 coord_fixed() scale_y_continuous(breaks = seq(50,80,5)) scale_x_continuous(breaks = seq(12,16,1))
15.breaks=NULL去除y或者x的刻度
sp1 scale_y_continuous(breaks = NULL) scale_x_continuous(breaks = NULL)
16.scale_y_continuous修改刻度上的标签
sp1 scale_y_continuous(breaks=c(50,55,60,65),labels = c("fifty","fifty-five","sixty","sixty-five"))
17.theme(axis.text.x=element_text)修改字体颜色
sp1 theme(axis.text.x =element_text(face = "italic",colour = "red",size=rel(2)), axis.text.y =element_text(face = "italic",colour = "blue",size=rel(2)))
18.xlab和ylab添加标题
sp1 xlab("这是x轴") ylab("这是y轴")
19.theme(axis.line=element_line(colour="black"))坐标轴更改颜色
# xy一起改
sp1 theme(axis.line = element_line(colour = "red")) # 只改一个轴
sp1 theme(axis.line.x = element_line(colour = "red",size = 1),axis.line.y=element_line(colour = "blue",size=2))
20.binwidth设置每个bin的宽度
ggplot(faithful,aes(waiting)) geom_histogram(binwidth = 5,fill="red", colour="blue",size=2)
,
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com