在Python中使用 Plotly 绘制 3D 散点图
Plotly是一个Python库,用于设计图形,尤其是交互式图形。它可以绘制各种图形和图表,如直方图、条形图、箱线图、散布图等等。它主要用于数据分析和财务分析。 plotly 是一个交互式可视化库。
Plotly 中的 3D 散点图
散点图可以与几个语义分组一起使用,这有助于在图中很好地理解。他们可以绘制二维图形,在使用色调、大小和样式参数的语义时,可以通过映射最多三个附加变量来增强这些图形。所有用于识别不同子集的参数控制视觉语义。使用冗余语义有助于使图形更易于访问。它可以使用 plotly.express 类的 scatter_3d函数创建。
Syntax: plotly.express.scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, text=None, hover_name=None, hover_data=None, custom_data=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, error_z=None, error_z_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, size_max=None, color_discrete_sequence=None, color_discrete_map={}, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, symbol_sequence=None, symbol_map={}, opacity=None, log_x=False, log_y=False, log_z=False, range_x=None, range_y=None, range_z=None, title=None, template=None, width=None, height=None)
Parameters:
data_frame (DataFrame or array-like or dict) – This argument needs to be passed for column names (and not keyword names) to be used.
x (str or int or Series or array-like) – Either a name of a column in data_frame, or a pandas Series or array_like object.
y (str or int or Series or array-like) – Either a name of a column in data_frame, or a pandas Series or array_like object.
color (str or int or Series or array-like) – Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks.
示例 1:使用 Iris 数据集
Python3
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x = 'sepal_width',
y = 'sepal_length',
z = 'petal_width',
color = 'species')
fig.show()
Python3
import plotly.express as px
df = px.data.tips()
fig = px.scatter_3d(df, x = 'total_bill',
y = 'day', z = 'time',
color = 'sex')
fig.show()
Python3
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x = 'sepal_width',
y = 'sepal_length',
z = 'petal_width',
color = 'species',
size='petal_length',
size_max = 20,
opacity = 0.5)
fig.show()
Python3
import plotly.express as px
df = px.data.tips()
fig = px.scatter_3d(df, x = 'total_bill',
y = 'day',
z = 'time',
color = 'sex',
size='tip',
size_max = 20,
opacity = 0.7)
fig.show()
输出:
示例 2:使用提示数据集
Python3
import plotly.express as px
df = px.data.tips()
fig = px.scatter_3d(df, x = 'total_bill',
y = 'day', z = 'time',
color = 'sex')
fig.show()
输出:
自定义 3D 散点图
在 Plotly 中,通过 px.scatter_3d 的参数,可以为某些选项自定义图形的样式。
示例 1:使用 Iris 数据集。
Python3
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x = 'sepal_width',
y = 'sepal_length',
z = 'petal_width',
color = 'species',
size='petal_length',
size_max = 20,
opacity = 0.5)
fig.show()
输出:
示例 2:使用提示数据集
Python3
import plotly.express as px
df = px.data.tips()
fig = px.scatter_3d(df, x = 'total_bill',
y = 'day',
z = 'time',
color = 'sex',
size='tip',
size_max = 20,
opacity = 0.7)
fig.show()
输出: