直方图

使用 ggplot2 进行数据可视化入门

Rick Scavetta

Founder, Scavetta Academy

常见图形类型

图形类型 可用 Geom
散点图 points, jitter, abline, smooth, count
条形图 histogram, bar, col, errorbar
折线图 line, path
使用 ggplot2 进行数据可视化入门

直方图

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram()
  • 将数值分箱后绘制
    • 即统计函数
`stat_bin()` using `bins = 30`.
Pick better value with `binwidth`.

使用 ggplot2 进行数据可视化入门

默认:30 个等宽箱

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram()
  • 将数值分箱后绘制
    • 即统计函数
# Default bin width:
diff(range(iris$Sepal.Width))/30
[1] 0.08

使用 ggplot2 进行数据可视化入门

直观且有意义的箱宽

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram(binwidth = 0.1)
  • 始终为数据设置有意义的箱宽。

  • 柱间无空隙。

使用 ggplot2 进行数据可视化入门

重新放置刻度线

ggplot(iris, aes(x = Sepal.Width)) + 
  geom_histogram(binwidth = 0.1,
                 center = 0.05)
  • 始终为数据设置有意义的箱宽。

  • 柱间无空隙。

  • X 轴刻度位于柱间。

使用 ggplot2 进行数据可视化入门

不同物种

ggplot(iris, aes(x = Sepal.Width, 
                 fill = Species)) + 
  geom_histogram(binwidth = .1, 
                 center = 0.05)

使用 ggplot2 进行数据可视化入门

默认位置为"stack"

ggplot(iris, aes(x = Sepal.Width,
                 fill = Species)) + 
  geom_histogram(binwidth = .1, 
                 center = 0.05,
                 position = "stack") 

使用 ggplot2 进行数据可视化入门

position = "dodge"

ggplot(iris, aes(x = Sepal.Width, 
                 fill = Species)) + 
  geom_histogram(binwidth = .1, 
                 center = 0.05, 
                 position = "dodge")

使用 ggplot2 进行数据可视化入门

position = "fill"

ggplot(iris, aes(x = Sepal.Width, 
                 fill = Species)) + 
  geom_histogram(binwidth = .1, 
                 center = 0.05, 
                 position = "fill")  

使用 ggplot2 进行数据可视化入门

结束幻灯片

使用 ggplot2 进行数据可视化入门

Preparing Video For Download...