渐变散点图

作者

[编辑] 郑虎;

[审核] .

注记

Hiplot 网站

本页面为 Hiplot Gradient Scatter 插件的源码版本教程,您也可以使用 Hiplot 网站实现无代码绘图,更多信息请查看以下链接:

https://hiplot.cn/basic/scatter-gradient?lang=zh_cn

二维空间散点展示多数值变量关系。

环境配置

  • 系统: Cross-platform (Linux/MacOS/Windows)

  • 编程语言: R

  • 依赖包: grafify; ggplot2

# 安装包
if (!requireNamespace("grafify", quietly = TRUE)) {
  install.packages("grafify")
}
if (!requireNamespace("ggplot2", quietly = TRUE)) {
  install.packages("ggplot2")
}

# 加载包
library(grafify)
library(ggplot2)

数据准备

# 加载数据
data <- read.delim("files/Hiplot/160-scatter-gradient-data.txt", header = T)

# 查看数据
head(data)
                car  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

可视化

# 渐变散点图
p <- ggplot(data, aes(x = mpg, y = disp)) + 
  geom_point(aes(fill = gear), size = 5, alpha = 1, shape = 21, stroke = 0.5) +
  labs(fill = "gear", color = "gear") +
  theme_classic(base_size = 10) +
  theme(strip.background = element_blank()) +
  guides(x = guide_axis(angle = 0)) +
  scale_fill_gradient(low = "#00438E", high = "#E43535") +
  scale_color_gradient(low = "#00438E", high = "#E43535") + 
  guides(fill = guide_legend(title = "gear"),
         size = guide_legend(title = "gear")) +
  ggtitle("Scatter-gradient Plot") +
  theme(text = element_text(family = "Arial"),
        plot.title = element_text(size = 12,hjust = 0.5),
        axis.title = element_text(size = 12),
        axis.text = element_text(size = 10),
        axis.text.x = element_text(angle = 0, hjust = 0.5,vjust = 1),
        legend.position = "right",
        legend.direction = "vertical",
        legend.title = element_text(size = 10),
        legend.text = element_text(size = 10))

p
图 1: 渐变散点图