Python 如何在Plotly中显示3D散点图中的图例和标签轴
Plotly是一个开源的Python库,用于创建图表。Python用户可以使用Plotly创建交互式的基于Web的可视化图表,可以在Jupyter笔记本中显示,保存为独立的HTML文件,或者作为Dash的一部分展示在Web应用中。
在本教程中,我们将展示如何使用Plotly在3D散点图中显示图例和标签轴。
- 这里,我们将使用 plotly.express 来生成图表。它包含许多自定义图表和将它们渲染为HTML格式的方法。
-
我们将使用 Pandas 模块来生成数据框。
-
此外,我们将使用 plotly.graphs_obj() 方法来生成带有不同绘图的图表。
按照下面给出的步骤来显示图例和标签轴。
步骤1
导入 plotly.express 模块并将其别名设置为 px 。
import plotly.express as px
步骤2
使用Pandas创建一个数据框。
data = {
'gadget' : ['mobile','tablet','ipad','laptop'],
'rating' :[3,4,2,1],
'price':[20000,50000,30000,90000]
}
df = pd.DataFrame(data)
步骤3
使用 scatter_3d() 方法通过应用X和y坐标值创建一个3D散点图 −
# Create scatter_3d plot
fig = px.scatter_3d(
df, x = 'gadget',
y = 'rating',z = 'price',
title="scatter 3D plot"
)
步骤4
使用 update_layout() 方法,使用以下属性更新布局-
fig.update_layout(
font_family="Courier New",
font_color="blue",
title_font_family="Times New Roman",
title_font_color="red",
legend_title_font_color="green"
)
示例
在3D散点图中显示图例和标签轴的完整代码如下:
import plotly.express as px
import pandas as pd
# Create DataFrame
data = {
'gadget' : ['mobile','tablet','ipad','laptop'],
'rating' :[3,4,2,1],
'price':[20000,50000,30000,90000]
}
df = pd.DataFrame(data)
# Create scatter_3d plot
fig = px.scatter_3d(df, x = 'gadget', y = 'rating',z = 'price', title="scatter 3D plot", width=716, height=750)
# Update the figure layout
fig.update_layout(
font_family="Courier New",
font_color="blue",
title_font_family="Times New Roman",
title_font_color="red",
legend_title_font_color="green"
)
fig.show()
输出
执行时,它将在浏览器上显示以下输出: