R可视化:ggplot2的基本原理和使用方法

ggplot2的基本原理和使用方法

ggplot2是R语言第三方可视化扩展包,在某种程度上它基本代替了R可视化。该包是RStudio首席科学家Hadley Wickham读博期间的作品,它强大的画图逻辑使得它称为R最流行的包之一。

Introduction

ggplot2 is based on the grammar of graphics, the idea that you can build every graph from the same few components: a data set, a set of geoms—visual marks that represent data points, and a coordinate system。

一张统计图形就是从数据几何对象(geometric object,缩写geom)的图形属性(aesthetic attribute,缩写aes)的一个映射。此外,图形中还可能包含数据的统计变换(statistical transformation,缩写stats),最后绘制在某个特定的坐标系(coordinate system,缩写coord)中,而分面(facet)则可以用来生成数据不同子集的图形。

To display data values, map variables in the data set to aesthetic properties of the geom like size, color, and x and y locations

Basic concept

  • 数据:data
  • 统计变换:stats
  • 几何对象:geom
  • 图形属性:aes
  • 标尺:scale
  • 图层:layer
  • 坐标系:coord
  • 分面:facet

Data and Mapping

aesthetic map variables in data to graphic properties. mappings control the relationship between data and graphic properties.

Aesthetic mapping means "something you can see"

  1. position (x, y axes)
  2. color ("outside" color)
  3. fill ("inside", color)
  4. shape (points)
  5. linetype
  6. size

Each type of geom accepts only a subset of all aesthetics-refer to the geom help pages to see what mappings each geom accepts. Aesthetic mappings are set with the aes() function.

Scale

scales map values in the data space to values in the aesthetic space(color, size, shape ...). scales are reported on the plot using axes and legends. Control aesthetic mapping.

Scales are modified with a series of functions using a scale_<aesthetic>_<type> naming scheme

  1. position
  2. color and fill
  3. size
  4. shape
  5. line type

The following arguments are common to most scales in ggplot2:

  1. name: the first argument gives the axis or legend title
  2. limits: the minimum and maximum of the scale
  3. breaks: the points along the scale where labels should appear
  4. labels: the labels that appear at each break
ggplot(housing,
       aes(x = State,
           y = Home.Price.Index)) + 
       theme(legend.position="top",
             axis.text=element_text(size = 6))+
    geom_point(aes(color = Date),
               alpha = 0.5,
               size = 1.5,
               position = position_jitter(width = 0.25, height = 0)))+
  scale_color_continuous(name="",
                         breaks = c(1976, 1994, 2013),
                         labels = c("'76", "'94", "'13"),
                         low = muted("blue"), high = muted("red"))

Geometic Objects (geom)

geometric objects are the actual marks we put on a plot

  1. points (geom_points, scatter plot, dot plot)
  2. lines (geom_lines, time series)
  3. boxplot (geom_boxplot, boxplot, barplot)

A plot must have at least one geometric object, and there is no upper limit. adding a geom by using the + operator.

Statistical Transformations

It's often useful to transform your data before plotting, and that's what statistical transformations do.

Statistic Explanation
stat_bin Statistics - (Discretizing|binning) (bin)
stat_smooth Statistic - Smooth (Function Continuity) (Soft ?)
stat_density Statistics - (Probability) Density Function (PDF)

Every geom function has a default statistic:

  1. geom_histogram = stat_bin + bar
  2. geom_smooth = stat_smooth + ribbon
  3. geom_density = stat_density + ribbon

Themes

The ggplot2 theme system handles non-data plot elements such as

  1. Axis labels
  2. Plot background
  3. Facet label backround
  4. Legend appearance

Built-in themes include:

  1. theme_gray() (default)
  2. theme_bw()
  3. theme_classc()
create a new theme
theme_new <- theme_bw() +
  theme(plot.background = element_rect(size = 1, color = "blue", fill = "black"),
        text=element_text(size = 12, family = "Serif", color = "ivory"),
        axis.text.y = element_text(colour = "purple"),
        axis.text.x = element_text(colour = "red"),
        panel.background = element_rect(fill = "pink"),
        strip.background = element_rect(fill = muted("orange")))

Facet

  • Faceting is ggplot2 parlance for small multiples
  • The idea is to create separate graphs for subsets of data
  • ggplot2 offers two functions for creating small multiples:
    • facet_wrap(): define subsets as the levels of a single grouping variable
    • facet_grid(): define subsets as the crossing of two grouping variables
  • Facilitates comparison among plots, not just of geoms within a plot
library(ggrepel)
library(ggplot2)
library(scales)

dat <- read.csv("EconomistData.csv")
mR2 <- summary(lm(HDI ~ CPI + log(CPI), data = dat))$r.squared
mR2 <- paste0(format(mR2, digits = 2), "%")
ggplot(dat,
            mapping = aes(x = CPI, y = HDI)) +
    geom_point(mapping = aes(color = Region),
               shape = 1,
               size = 4,
               stroke = 1.5) +
    geom_smooth(mapping = aes(linetype = "r2"),
                method = "lm",
                formula = y ~ x + log(x), se = FALSE,
                color = "red") +
    geom_text_repel(mapping = aes(label = Country, alpha = labels),
                    data = transform(dat,
                                     labels = Country %in% c("Russia",
                                                             "Venezuela",
                                                             "Iraq",
                                                             "Mayanmar",
                                                             "Sudan",
                                                             "Afghanistan",
                                                             "Congo",
                                                             "Greece",
                                                             "Argentinia",
                                                             "Italy",
                                                             "Brazil",
                                                             "India",
                                                             "China",
                                                             "South Africa",
                                                             "Spain",
                                                             "Cape Verde",
                                                             "Bhutan",
                                                             "Rwanda",
                                                             "France",
                                                             "Botswana",
                                                             "France",
                                                             "US",
                                                             "Germany",
                                                             "Britain",
                                                             "Barbados",
                                                             "Japan",
                                                             "Norway",
                                                             "New Zealand",
                                                             "Sigapore"))) +
    scale_x_continuous(name = "Corruption Perception Index, 2011 (10=least corrupt)",
                       limits = c(1.0, 10.0),
                       breaks = 1:10) +
    scale_y_continuous(name = "Human Development Index, 2011 (1=best)",
                       limits = c(0.2, 1.0),
                       breaks = seq(0.2, 1.0, by = 0.1)) +
    scale_color_manual(name = "",
                       values = c("#24576D",
                                  "#099DD7",
                                  "#28AADC",
                                  "#248E84",
                                  "#F2583F",
                                  "#96503F"),
                       guide = guide_legend(nrow = 1)) +
    scale_alpha_discrete(range = c(0, 1),
                         guide = FALSE) +
    scale_linetype(name = "",
                   breaks = "r2",
                   labels = list(bquote(R^2==.(mR2))),
                   guide = guide_legend(override.aes = list(linetype = 1, size = 2, color = "red"))) +
    ggtitle("Corruption and human development") +
    theme_bw() +
    theme(panel.border = element_blank(),
          panel.grid = element_blank(),
          panel.grid.major.y = element_line(color = "gray"),
          axis.line.x = element_line(color = "gray"),
          axis.text = element_text(face = "italic"),
          legend.position = "top",
          legend.direction = "horizontal",
          legend.box = "horizontal",
          legend.text = element_text(size = 12),
          plot.title = element_text(size = 16, face = "bold"))

参考

  1. ggplot2
  2. ggplot2 packages
  3. ggplot2简介
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,968评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,601评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,220评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,416评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,425评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,144评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,432评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,088评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,586评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,028评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,137评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,783评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,343评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,333评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,559评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,595评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,901评论 2 345