# 安装包
if (!requireNamespace("data.table", quietly = TRUE)) {
install.packages("data.table")
}if (!requireNamespace("jsonlite", quietly = TRUE)) {
install.packages("jsonlite")
}if (!requireNamespace("grafify", quietly = TRUE)) {
install.packages("grafify")
}if (!requireNamespace("ggplot2", quietly = TRUE)) {
install.packages("ggplot2")
}
# 加载包
library(data.table)
library(jsonlite)
library(grafify)
library(ggplot2)
渐变散点图
注记
Hiplot 网站
本页面为 Hiplot Gradient Scatter
插件的源码版本教程,您也可以使用 Hiplot 网站实现无代码绘图,更多信息请查看以下链接:
二维空间散点展示多数值变量关系。
环境配置
系统: Cross-platform (Linux/MacOS/Windows)
编程语言: R
依赖包:
data.table
;jsonlite
;grafify
;ggplot2
数据准备
# 加载数据
<- data.table::fread(jsonlite::read_json("https://hiplot.cn/ui/basic/scatter-gradient/data.json")$exampleData[[1]]$textarea[[1]])
data <- as.data.frame(data)
data
# 查看数据
head(data[,1:5])
car mpg cyl disp hp
1 Mazda RX4 21.0 6 160 110
2 Mazda RX4 Wag 21.0 6 160 110
3 Datsun 710 22.8 4 108 93
4 Hornet 4 Drive 21.4 6 258 110
5 Hornet Sportabout 18.7 8 360 175
6 Valiant 18.1 6 225 105
可视化
# 渐变散点图
<- ggplot(data, aes(x = mpg, y = disp)) +
p 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
