学好R语言绘图,你只需这样一个网站就够了

2020-10-30 15:17发布

话不多说,上网址:
https://www.r-graph-gallery.com/
r-garp-gallery收入了大量利用R语言绘制的图形,这些图形包含了很多方面,通过这个网站,我们可以方便直观观察到R语言所能做的一些图形。

1

  •  1. 网站对绘图进行了分类
    2

  •  2. 网站提供搜索功能,可以搜索需要的图形类型,例如heatmap
    3

  •  3. 每一个图形都给出了代码
    4

  •  4. 将代码复制到Rstudio中逐条运行
    5

2. 样例展示

2.1 词云

  •  1. 安装所需要的包

  •  2. 载入相关的包

  •  3.绘制词云

# Change the shape:wordcloud2(demoFreq, size = 0.7, shape = 'star')# Change the shape using your imagewordcloud2(demoFreq, figPath = "~/Desktop/R-graph-gallery/img/other/peaceAndLove.jpg", size = 1.5, color = "skyblue", backgroundColor="black")12345

8

2.2 气泡图

  •  1. 安装所需要的包
    9

  •  2. 载入安装包

  •  3. 最基本的气泡图 geom_point()

data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)# Most basic bubble plotggplot(data, aes(x=gdpPercap, y=lifeExp, size = pop)) +
  geom_point(alpha=0.7)12345

11

  •  4. 用 scale_size()

我们需要在上一张图表上改进的第一件事是气泡大小。scale_size()允许使用range参数设置最小和最大圆圈的大小。请注意,您可以使用来定制图例名称name。

data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)# Most basic bubble plotdata %>%
  arrange(desc(pop)) %>%
  mutate(country = factor(country, country)) %>%
  ggplot(aes(x=gdpPercap, y=lifeExp, size = pop)) +
    geom_point(alpha=0.5) +
    scale_size(range = c(.1, 24), name="Population (M)")123456789

12

  •  5. 添加第四个维度:颜色

data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)data %>%
  arrange(desc(pop)) %>%
  mutate(country = factor(country, country)) %>%
  ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, color=continent)) +
    geom_point(alpha=0.5) +
    scale_size(range = c(.1, 24), name="Population (M)")12345678

13

  •  6. 变得漂亮

一些经典的改进:

使用viridis包装获得漂亮的调色板
使用的theme_ipsum()所述的hrbrthemes包
定制轴职称xlab和ylab
将笔划添加到圆圈:更改shape为21并指定color(笔划)和fill

# Librarieslibrary(ggplot2)library(dplyr)library(hrbrthemes)library(viridis)# The dataset is provided in the gapminder librarylibrary(gapminder)data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)# Most basic bubble plotdata %>%
  arrange(desc(pop)) %>%
  mutate(country = factor(country, country)) %>%
  ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, fill=continent)) +
    geom_point(alpha=0.5, shape=21, color="black") +
    scale_size(range = c(.1, 24), name="Population (M)") +
    scale_fill_viridis(discrete=TRUE, guide=FALSE, option="A") +
    theme_ipsum() +
    theme(legend.position="bottom") +
    ylab("Life Expectancy") +
    xlab("Gdp per Capita") +
    theme(legend.position = "none")1234567891011121314151617181920212223

14

3. 总结

通过不断地对比,是不是发现原来用R语言绘图狠简单,作者由于时间有限,只能列出几个出来,剩下的要靠大家自己进行挖掘尝试。

转载自:CSDN   作者:不温卜火

原文链接:https://blog.csdn.net/qq_16146103/article/details/105602881