在Python中使用 Plotly 的树形图
Plotly是一个Python库,用于设计图形,尤其是交互式图形。它可以绘制各种图形和图表,如直方图、条形图、箱线图、散布图等等。它主要用于数据分析和财务分析。 plotly 是一个交互式可视化库。
Plotly 中的树形图
plotly.express中的treemap使用方便,高级终端绘图,完成多种类型的数据,生成易于样式的图形。树形图提供了数据的分层视图,并且可以轻松地涂抹模式。树枝以矩形为特征,每个子分支都显示在一个较小的矩形中。
Syntax: plotly.express.treemap(data_frame=None, names=None, values=None, parents=None, ids=None, path=None, color=None, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, color_discrete_sequence=None, color_discrete_map={}, hover_name=None, hover_data=None, custom_data=None, labels={}, title=None, template=None, width=None, height=None, branchvalues=None, maxdepth=None)
Parameters:
data_frame: This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame.
names: 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 as labels for sectors.
values: 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 set values associated to sectors.
path: Either names of columns in data_frame, or pandas Series, or array_like objects List of columns names or columns of a rectangular dataframe defining the hierarchy of sectors, from root to leaves.
color: 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.
例子:
Python3
import plotly.express as px
fig = px.treemap(
names = ["A","B", "C", "D", "E"],
parents = ["", "A", "B", "C", "A"]
)
fig.show()
Python3
Python3
import plotly.express as px
df = px.data.tips()
fig = px.treemap(df, path=['day', 'time', 'tip'],
values='total_bill')
fig.show()
Python3
import plotly.express as px
df = px.data.tips()
fig = px.treemap(df, path=['day', 'time', 'tip'],
values='total_bill',
color='total_bill')
fig.show()
Python3
import plotly.express as px
df = px.data.tips()
fig = px.treemap(df, path=['day', 'time', 'tip'],
values='total_bill',
color='sex')
fig.show()
输出:
绘制分层数据帧的树形图
矩形数据框通常以分层形式存储,其中列的不同对应于层次结构的不同级别。 px.treemap 可以使用与列列表对应的路径参数,但如果路径已经使用,则应提供 id 和 parent。
例子:
Python3
Python3
import plotly.express as px
df = px.data.tips()
fig = px.treemap(df, path=['day', 'time', 'tip'],
values='total_bill')
fig.show()
输出:
使用连续颜色参数绘制分层数据框
如果传递了颜色参数,则其子节点的颜色值的平均值(按其值加权)应由节点的颜色计算。
例子:
Python3
import plotly.express as px
df = px.data.tips()
fig = px.treemap(df, path=['day', 'time', 'tip'],
values='total_bill',
color='total_bill')
fig.show()
输出:
使用离散颜色参数绘制分层数据框
当非数字数据与颜色参数对应时,则使用离散颜色。如果所有扇区的颜色列的值都相同,则使用对应的颜色,否则使用序列中离散颜色的第一个颜色。
例子:
Python3
import plotly.express as px
df = px.data.tips()
fig = px.treemap(df, path=['day', 'time', 'tip'],
values='total_bill',
color='sex')
fig.show()
输出: