ggplot2 可视化 Part 2- swirl course

在part 1里我们了解了ggplot2的基本绘图功能qplot, 这次我们来看看另一个重要功能qplot

七个图形对象

  • DATA FRAME 数据帧
  • AESTHETIC MAPPINGS 外观图法
  • GEOMS 几何对象
  • FACETS 面板
  • STAT 统计转换,比如bin, smooth
  • SCALES ??
  • COORDINATE SYSTEM 坐标系

ggplot2绘图分步显示

使用层来建立图形

  • Plot the data 先对数据绘图
  • Overlay a summary 再把数据概要覆盖在数据图形上面
  • Metadata and annotation 最后是元数据和注释
qplot(displ, hwy, data=mpg, geom=c("point", "smooth"), facets=.~drv)
散点图-3面板

分步解读画图步骤

>g <- ggplot(mpg,aes(displ, hwy))
> summary(g)
data: manufacturer, model, displ, year, cyl, trans, drv, cty, hwy, fl,
  class [234x11]
mapping:  x = ~displ, y = ~hwy
faceting: 
    compute_layout: function
    draw_back: function
    draw_front: function
    draw_labels: function
    draw_panels: function
    finish_data: function
    init_scales: function
    map_data: function
    params: list
    setup_data: function
    setup_params: function
    shrink: TRUE
    train_scales: function
    vars: function
    super:  

从摘要中可以看出gg对象中包括:data(mpg), mapping(x,y), faceting(no)

> print(g)
# ggplot 不能用print打印gg对象
g + geom_point()
# 增加平滑曲线
g + geom_point() + geom_smooth()
# 改变平滑功能参数为线性回归
g + geom_point() + geom_smooth(method="lm")
# 子面板分组绘图
g + geom_point() + geom_smooth(method="lm") + facet_grid(. ~ drv)


增加注释

g + geom_point() + geom_smooth(method="lm") + facet_grid(.~drv) + ggtitle("Swirl Rules!")
增加绘图主标题

下面开始来改变图形的外观AESTHETIC, 设置散点的大小,颜色,透明度

 g + geom_point(color="pink", size=4, alpha=1/2)
外观设置,颜色深的表示数据有重叠

按颜色分组,设置aes clor 到一个因子变量,实现不同颜色变量的分组显示

g + geom_point(aes(color = drv), size = 4, alpha = 1/2)
设置color=factor变量

设置标题和标签 (图略)

g + geom_point(aes(color = drv)) + labs(title="Swirl Rules!") +  labs(x="Displacement", y="Hwy Mileage") 

定制平滑线

g + geom_point(aes(color = drv),size=2,alpha=1/2) + geom_smooth(size=4,linetype=3,method="lm",se=FALSE)

ggplot图层的复杂例子

> head(testdat)
  x           y
1 1 -1.13782391
2 2  0.57977757
3 3 -0.87085224
4 4 -0.39750827
5 5  0.08576791
6 6  0.92132965
# R原生画图
plot(myx, myy, type = "l", ylim = c(-3,3))

# ggplot 图层演示
g <- ggplot(testdat, aes(x = myx, y = myy))
# 对比原生绘图函数,离线点50,100会压缩整个图形
g + geom_line()
# 显示y轴数值范围,但是图形有中断
g + geom_line() + ylim(-3,3)
# 选择合适的坐标系,笛卡尔坐标,同时设置y轴范围
g + geom_line() + coord_cartesian(ylim=c(-3,3))
plog原生画图
ggplot, 离群点没有丢弃
ggplot,设置y轴范围,图形不连续
ggplot, 设置坐标系

继续以mpg数据集演示

> g <- ggplot(mpg,aes(x=displ,y=hwy,color=factor(year)))
...没有图形显示,因为没有定义图层

> g + geom_point()

子面板分组显示

> g + geom_point() + facet_grid(drv ~ cyl, margins=TRUE)

你可能感兴趣的:(ggplot2 可视化 Part 2- swirl course)