R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图

原文刊在这里,公众号:数与图

不同图表的实现-R语言ggplot2基础教程

一个有效的图表是:

传达正确的信息、不扭曲事实。 简单而优雅。 凸显特征,而不是掩盖信息。 不会信息过载(元素过多)。

下面的列表根据其主要目的对可视化方法进行了分类。在你真正做图之前,试着想一想,你想通过可视化来传达或研究什么结论和关系。根据目的去选择不同的图表类型(很可能就是如下类型的一种或多种)

相关
    Scatterplot
    Scatterplot With Encircling
    Jitter Plot
    Counts Chart
    Bubble Plot
    Animated Bubble Plot
    Marginal Histogram / Boxplot
    Correlogram
偏差
    Diverging Bars
    Diverging Lollipop Chart
    Diverging Dot Plot
    Area Chart
排名
    Ordered Bar Chart
    Lollipop Chart
    Dot Plot
    Slope Chart
    Dumbbell Plot
分布
    Histogram
    Density Plot
    Box Plot
    Dot + Box Plot
    Tufte Boxplot
    Violin Plot
    Population Pyramid
构成
    Waffle Chart
    Pie Chart
    Treemap
    Bar Chart
变化
    Time Series Plots
        From a Data Frame
        Format to Monthly X Axis
        Format to Yearly X Axis
        From Long Data Format
        From Wide Data Format
    Stacked Area Chart
    Calendar Heat Map
    Slope Chart
    Seasonal Plot
分组
    Dendrogram
    Clusters
空间可视化
    Open Street Map
    Google Road Map
    Google Hybrid Map

Correlation

The following plots help to examine how well correlated two variables are. Scatterplot

在数据分析中,最常用的图无疑是散点图。每当你想了解两个变量之间关系的性质时,首先选择的就是散点图。

它可以用geom_point()来绘制。此外,geom_smooth默认情况下会绘制一条平滑线(基于loess),可以通过设置方法=’lm’来绘制最佳拟合线。

options(scipen=999)  # turn-off scientific notation like 1e+48
library(ggplot2)
theme_set(theme_bw())  # pre-set the bw theme.
data("midwest", package = "ggplot2")

# Scatterplot
gg <- ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state, size=popdensity)) + 
  geom_smooth(method="loess", se=F) + 
  xlim(c(0, 0.1)) + 
  ylim(c(0, 500000)) + 
  labs(subtitle="Area Vs Population", 
       y="Population", 
       x="Area", 
       title="Scatterplot", 
       caption = "Source: midwest")

plot(gg)
## `geom_smooth()` using formula 'y ~ x'
## Warning: Removed 15 rows containing non-finite values (stat_smooth).
## Warning: Removed 15 rows containing missing values (geom_point).

R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图_第1张图片

Scatterplot With Encircling

在显示结果的时候,有时我会在图表中把某些特殊的点或区域包围起来,以引起人们对这些特殊情况的注意。这可以使用 ggalt 包中的 geom_encircle() 来方便地完成。

在geom_encircle()中,将数据设置为一个新的数据框,该数据框中只包含点(行)或感兴趣的点。此外,你可以将曲线展开,以便在点的外侧传递。曲线的颜色和大小(厚度)也可以修改。请看下面的例子。

options(scipen = 999)
library(ggplot2)
library(ggalt)
midwest_select <- midwest[midwest$poptotal > 350000 & 
                            midwest$poptotal <= 500000 & 
                            midwest$area > 0.01 & 
                            midwest$area < 0.1, ]

# Plot
ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state, size=popdensity)) +   # draw points
  geom_smooth(method="loess", se=F) + 
  xlim(c(0, 0.1)) + 
  ylim(c(0, 500000)) +   # draw smoothing line
  geom_encircle(aes(x=area, y=poptotal), 
                data=midwest_select, 
                color="red", 
                size=2, 
                expand=0.08) +   # encircle
  labs(subtitle="Area Vs Population", 
       y="Population", 
       x="Area", 
       title="Scatterplot + Encircle", 
       caption="Source: midwest")
## `geom_smooth()` using formula 'y ~ x'
## Warning: Removed 15 rows containing non-finite values (stat_smooth).
## Warning: Removed 15 rows containing missing values (geom_point).

R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图_第2张图片

Jitter Plot

让我们来看一个新的数据来绘制散点图。这一次,我将使用mpg数据集绘制城市里程数(cty)vs高速公路里程数(hwy)。

library(ggplot2)
data(mpg, package="ggplot2") # alternate source: "http://goo.gl/uEeRGu")
theme_set(theme_bw())  # pre-set the bw theme.

g <- ggplot(mpg, aes(cty, hwy))

# Scatterplot
g + geom_point() + 
  geom_smooth(method="lm", se=F) +
  labs(subtitle="mpg: city vs highway mileage", 
       y="hwy", 
       x="cty", 
       title="Scatterplot with overlapping points", 
       caption="Source: midwest")
## `geom_smooth()` using formula 'y ~ x'

R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图_第3张图片

ggplot2 Scatterplot With Hidden Data points

我们这里有一个城市和高速公路里程数的散点图,在mpg数据集中。我们已经看到了一个类似的散点图,这个看起来很整洁,并给出了一个清晰的想法,城市里程数(cty)和高速公路里程数(hwy)是如何很好的相关性。

但是,这个看起来天真烂漫的散点图却隐藏着一些东西。你能发现吗?

dim(mpg)
## [1] 234  11

原来的数据有234个数据点,但图表中显示的点似乎少了。这是怎么回事呢?这是因为有很多重叠的点以单个点的形式出现。事实上,源数据集中的cty和hwy都是整数,这使得隐藏这个细节更加方便。所以下次用整数做散点图时要格外小心。

那么,如何处理这个问题呢?有几个选择。我们可以用jitter_geom()做一个抖动图。顾名思义,重叠的点会根据宽度参数控制的阈值在其原始位置附近随机抖动。

# load package and data
library(ggplot2)
data(mpg, package="ggplot2")
# mpg <- read.csv("http://goo.gl/uEeRGu")

# Scatterplot
theme_set(theme_bw())  # pre-set the bw theme.
g <- ggplot(mpg, aes(cty, hwy))
g + geom_jitter(width = .5, size=1) +
  labs(subtitle="mpg: city vs highway mileage", 
       y="hwy", 
       x="cty", 
       title="Jittered Points")

R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图_第4张图片

Counts Chart

第二种克服数据点重叠问题的方法是使用所谓的计数图。只要重叠点多的地方,圆的大小就会变大。

# load package and data
library(ggplot2)
data(mpg, package="ggplot2")
# mpg <- read.csv("http://goo.gl/uEeRGu")

# Scatterplot
theme_set(theme_bw())  # pre-set the bw theme.
g <- ggplot(mpg, aes(cty, hwy))
g + geom_count(col="tomato3", show.legend=F) +
  labs(subtitle="mpg: city vs highway mileage", 
       y="hwy", 
       x="cty", 
       title="Counts Plot")

R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图_第5张图片

Bubble plot

虽然散点图可以让你比较2个连续变量之间的关系,但如果你想了解底层组内的关系,泡泡图的作用是很好的。

一个分类变量(通过改变颜色)和
另一个是连续变量(通过改变点的大小)。

用更简单的话说,如果你有4维数据,其中两个是数字变量(X和Y),另一个是分类变量(颜色),另一个是数字变量(大小),那么气泡图就更适合。

泡泡图可以清楚地区分出厂商之间的drop范围,以及最佳拟合线的斜率是如何变化的,为组间的比较提供了更好的视觉效果。

# load package and data
library(ggplot2)
data(mpg, package="ggplot2")
# mpg <- read.csv("http://goo.gl/uEeRGu")

mpg_select <- mpg[mpg$manufacturer %in% c("audi", "ford", "honda", "hyundai"), ]

# Scatterplot
theme_set(theme_bw())  # pre-set the bw theme.
g <- ggplot(mpg_select, aes(displ, cty)) + 
  labs(subtitle="mpg: Displacement vs City Mileage",
       title="Bubble chart")

g + geom_jitter(aes(col=manufacturer, size=hwy)) + 
  geom_smooth(aes(col=manufacturer), method="lm", se=F)
## `geom_smooth()` using formula 'y ~ x'

R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图_第6张图片

Animated Bubble chart

可以使用gganimate包实现一个动画气泡图。它和气泡图一样,但是,显示值在第五维(通常是时间)上的变化。

最关键的是将 aes(frame)设置为你想要动画化的列。其他与绘图构建相关的过程是一样的。一旦构建好图形后,你可以通过设置一个选择的区间,使用 gganimate()对其进行动画化。

library(ggplot2)
library(gganimate)
library(gapminder)
theme_set(theme_bw())  # pre-set the bw theme.

g <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop,frame=year)) +
  geom_point() +
  facet_wrap(~continent, scales = "free") +
  scale_x_log10()+
  transition_time(year)
g

R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图_第7张图片

# animate(g, interval=0.2)

Marginal Histogram / Boxplot

如果你想在同一图表中显示关系以及分布,可以使用边际直方图。它在散点图的边缘有一个X和Y变量的直方图。

这可以使用’ggExtra’包中的gggMarginal()函数来实现。除了直方图之外,你还可以通过设置相应的类型选项来绘制边际boxplot或密度图。

# load package and data
library(ggplot2)
library(ggExtra)
data(mpg, package="ggplot2")

# Scatterplot
theme_set(theme_bw())  # pre-set the bw theme.
mpg_select <- mpg[mpg$hwy >= 35 & mpg$cty > 27, ]
g <- ggplot(mpg, aes(cty, hwy)) + 
  geom_count() + 
  geom_smooth(method="lm", se=F)
g
## `geom_smooth()` using formula 'y ~ x'
ggMarginal(g, type = "histogram", fill="transparent")
## `geom_smooth()` using formula 'y ~ x'
## `geom_smooth()` using formula 'y ~ x'
ggMarginal(g, type = "boxplot", fill="transparent")
## `geom_smooth()` using formula 'y ~ x'
## `geom_smooth()` using formula 'y ~ x'

R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图_第8张图片

# ggMarginal(g, type = "density", fill="transparent")

Correlogram

Correlogram可以检验同一个数据框中存在的多个连续变量的相关性。这可以用gggcorrplot包来实现,非常方便。

# devtools::install_github("kassambara/ggcorrplot")
library(ggplot2)
library(ggcorrplot)

# Correlation matrix
data(mtcars)
corr <- round(cor(mtcars), 1)

# Plot
ggcorrplot(corr, hc.order = TRUE, 
           type = "lower", 
           lab = TRUE, 
           lab_size = 3, 
           method="circle", 
           colors = c("tomato2", "white", "springgreen3"), 
           title="Correlogram of mtcars", 
           ggtheme=theme_bw)

R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图_第9张图片

你可能感兴趣的:(R语言可视化进阶-高级点图、气泡图、动态图、图形叠加与相关图)