R图表入门

R图表入门

R语言最强的功能就是统计和作图了,在学习了基本语法之后,博主马上体验了一下R的图表功能

条形图

例1

H = c(7,12,28,3,41)
M = c("Mar","Apr","May","Jun","Jul")

barplot(H, #数据集
        names.arg = M, #坐标项名称
        xlab = "Revenue", #坐标标签
        ylab = "Month", #坐标标签
        col = "blue", #主体颜色
        border = "red", #边缘颜色
        main = "Revenue chart", #标题
        horiz = TRUE) #水平方向

1146398-20171002143623615-1795405225.png

例2

colors = c("green","orange","brown")
months = c("Mar","Apr","May","Jun","Jul")
regions = c("East","West","North")

values = matrix(1:15,nrow = 3)
#调用系统字体显示中
#这里使用了黑体
par( family = 'Hei')
barplot(values, main = "主题",
        names.arg = months,
        xlab = "Month",
        ylab = "revene",
        col = colors)
legend("topleft",regions,
       cex = 1.3,
       fill = colors)

1146398-20171002143633786-563965998.png

箱式图

input = mtcars[,c('mpg','cyl')] #取mtcars做测试
boxplot(mpg ~ cyl, #mpg关于不同cyl的的分布
        data = mtcars, 
        xlab = "Number of Cylinders",
        ylab = "Miles Per Gallon", 
        main = "Mileage Data",
        # notch = TRUE, #带槽的图
        # varwidth = FALSE, 
        col = c("green","yellow","purple"),
        names = c("High","Medium","Low"))

1146398-20171002143643740-1130847416.png

直方图

input = mtcars[,c('mpg')] #取mtcars做测试
hist(
    input,
    main = "Histogram exalple",
    xlab = "x",
    ylab = "y",
    col = "green",
    border = "brown",
    breaks = 10 #分割10次,共11段
)
print(input)

1146398-20171002143653083-460417634.png

折线图&散点图

v = c(7,12,28,3,41)
#在没有y的情况下,横坐标默认为1,2,3……
#type为图像类型,p为点,l为线,o为点线
plot(v, type = "p", col = "red", main = "theme")
#lines函数可以画多条线
lines(20:50,type = "o", col = "green")

1146398-20171002143703177-1194857927.png

饼图

例1

x = c(21,62,10,53)
labels = c("London", "New york", "Singapore", "Mumbai")
labels = c("London", "New york", "Singapore", "Mumbai")
piepercent = paste( round(100*x/sum(x), digits = 2),'%',seq = '') #计算百分比
pie(x, paste(labels,piepercent),
    main = "City pie chart",
    #可以使用彩虹函数设置颜色
    col = rainbow(length(x),alpha = 0.5)
    )

legend("topright",
       labels,
       cex = 0.8, #调整大小,1为正常
       fill = rainbow(length(x),alpha = 0.5))

1146398-20171002143712677-113042943.png

例2

3D饼图

# library(plotrix)
x = c(21,62,10,53)
lbl = c("London","New York","Singapore","Mumbai")
plotrix::pie3D(x,labels = lbl,explode = 0.1, main = "3D Pie Chart")

1146398-20171002143723146-846895965.png

保存到本地

H = c(7,12,28,3,41)

# 创建一个图形的Device
png(file = "barchart.png")

# 在Device上作图
barplot(H)

# 关闭Device(保存)
dev.off()

小结

博主这里学习了R语言基础的作图方法,大体上已经够用,更高阶的应该要请大名鼎鼎的ggplot2登场,以后有机会再学习。

转载于:https://www.cnblogs.com/fanghao/p/7620117.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值