R可视化和ggplot2

1-ggplot2

2019-08-24  本文已影响0人  泥人吴
准备工作
#安装tidyverse
install.packages("tidyverse")
# 加载tidyverse
library(tidyverse)

1.2.2 创建ggplot图形

ggplot(data = mpg)+
       geom_point(mapping = aes(x=displ,y=hwy))
  • mapping参数没定义了如何将数据集中的变量映射为图形属性。mapping总是与aes()函数成对出现。

1.3图形属性映射

# 颜色
ggplot(data = mpg)+
        geom_point(mapping = aes(x=displ,y=hwy,,color=class))
#大小size
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, size = class))

1.5分页

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) + 
  facet_wrap(~ class, nrow = 2)
# 按照~class分类,两行nrow=2

nrow指定分面后显示几行
ncol指定分面后显示几列
注意~分面依据必须离散型变量

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) + 
  facet_grid(drv ~ cyl)

1.6对象

# left
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy))

# right
ggplot(data = mpg) + 
  geom_smooth(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg) + 
  geom_smooth(mapping = aes(x = displ, y = hwy, linetype = drv))
#隐式分组-线型(下图)

#隐式分组-颜色
ggplot(data = mpg) +
  geom_smooth(
    mapping = aes(x = displ, y = hwy, color = drv),
    show.legend = FALSE  #不显示图例
  )
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) +
  geom_smooth(mapping = aes(x = displ, y = hwy))
# 全局映射
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + 
  geom_point() + 
  geom_smooth()
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
  geom_point(mapping = aes(color = class)) +
  geom_smooth()

1.7统计转换

1.8 位置调整

(1)直方图之堆叠式-fill
# left
ggplot(data = diamonds) +
       geom_bar(mapping = aes(x = cut, color = cut))
# right
ggplot(data = diamonds) +
       geom_bar(mapping = aes(x = cut, fill = cut))
# 所以fill和color表示不同
(2)直方图之对象直接显示-identity
ggplot(data = diamonds, mapping = aes(x = cut, fill = clarity)) + 
  geom_bar(alpha = 1/5, position = "identity")
ggplot(data = diamonds, mapping = aes(x = cut, colour = clarity)) + 
  geom_bar(fill = NA, position = "identity")
(3)直方图之并列式-dodge
ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")
(4)散点图之扰动-jitter
# 原始散点图
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy))
#扰动后:
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy), position = "jitter")

1.9 坐标系

(1)coord_flip翻转坐标系
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
       geom_boxplot()
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
       geom_boxplot() +
       coord_flip()
(3)coord_polar 极坐标系
bar <- ggplot(data = diamonds) + 
  geom_bar(
    mapping = aes(x = cut, fill = cut), 
    show.legend = FALSE,
    width = 1
  ) + 
  theme(aspect.ratio = 1) +
  labs(x = NULL, y = NULL)
print(bar)
bar + coord_flip() #箱图倒置
bar + coord_polar() #鸡冠图
上一篇 下一篇

猜你喜欢

热点阅读