R中的3D气泡图
在本文中,我们将讨论如何在 R 语言中创建 3D 气泡图。
气泡图主要用于描述和显示数值变量之间的关系。它可以比散点图更好地显示关系,因为它具有额外的维度大小,可以帮助我们分析数据的更多方面,从而使其成为多维分析。
Install - install.packages("Plotly")
plot_ly()函数创建一个 3D 散点图,但通过向其添加尺寸维度。
Syntax:
plot_ly(df, x, y, z, color, size)
where,
- df: determines the data frame to be used.
- x,y, and z: determine the x-axis, y-axis, and z-axis variables respectively.
- color: determines the categorical variable according to which bubbles are to be colored.
- size: determines the categorical variable according to which bubbles are to be sized.
示例 1:
这是一个基本的 3D 气泡图。示例中使用的 CSV 文件可在此处下载。
R
# load library Plotly and tidyverse
library(plotly)
library(tidyverse)
# read csv file into dataframe
df <- read.csv("df.csv")
# plot 3d bubble plot
plot_ly(df, x = ~pop, y = ~gdpPercap, z = ~lifeExp, size = ~size )
R
# load library Plotly and tidyverse
library(plotly)
library(tidyverse)
# read csv file into dataframe
df <- read.csv("df.csv")
# plot 3d bubble plot
# color plot by continent column using color parameter
plot_ly(df, x = ~pop, y = ~gdpPercap, z = ~lifeExp, size = ~size, color=~continent )
R
# load library Plotly and tidyverse
library(plotly)
library(tidyverse)
# read csv file into dataframe
df <- read.csv("df.csv")
# plot 3d bubble plot
# color plot by continent column using
# color parameter
plot<-plot_ly(df, x = ~pop, y = ~gdpPercap, z = ~lifeExp,
size = ~size, color=~continent)
# layout customization is used to customize plot
plot%>% layout( title = 'Geeksforgeeks example',
paper_bgcolor = 'gray')
输出:
示例 2:
这是一个基本的 3D 气泡图,由分类变量使用 plot_ly()函数的颜色参数着色。示例中使用的 CSV 文件可在此处下载。
R
# load library Plotly and tidyverse
library(plotly)
library(tidyverse)
# read csv file into dataframe
df <- read.csv("df.csv")
# plot 3d bubble plot
# color plot by continent column using color parameter
plot_ly(df, x = ~pop, y = ~gdpPercap, z = ~lifeExp, size = ~size, color=~continent )
输出:
自定义 3D 绘图
我们可以使用绘图布局函数的各种参数来自定义这个 3D 绘图。我们可以使用 paper_bgcolor、plot_bgcolor 和 title 参数来分别改变绘图周围的颜色、绘图的背景颜色和绘图的标题。
Syntax:
plot%>%layout( title, paper_bgcolor, plot_bgcolor)
where,
- title: determines the title of the plot.
- paper_bgcolor: determines the color of the surrounding of the plot.
- plot_bgcolor: determines the color of the background of the plot.
示例 1:
这是一个完全定制的 3D 气泡图。示例中使用的 CSV 文件可在此处下载。
R
# load library Plotly and tidyverse
library(plotly)
library(tidyverse)
# read csv file into dataframe
df <- read.csv("df.csv")
# plot 3d bubble plot
# color plot by continent column using
# color parameter
plot<-plot_ly(df, x = ~pop, y = ~gdpPercap, z = ~lifeExp,
size = ~size, color=~continent)
# layout customization is used to customize plot
plot%>% layout( title = 'Geeksforgeeks example',
paper_bgcolor = 'gray')
输出: