使用 PLOTLY 的颜色编码树图
Color coding Tree map with PLOTLY
我的要求是使用 python 绘制树图,我正在使用 plotly 来实现相同的...
接近我实时数据的Data frame如下
import pandas as pd
import plotly.express as px
data_frame = pd.DataFrame({'region':['AA','AB','AC','AD','AE'],
'number':[2,12,6,11,30],
'percentage':[94.03,91.23,95.66,97.99,99.22]})
下面代码中的情节看起来像这样
fig = px.treemap(data_frame, path= [data_frame['region']],
values=data_frame['number'],color=data_frame['percentage'])
fig.show()
剧情
但是,我想要基于“百分比”列的颜色编码,自定义比例如下
- data_frame['percentage'] > 98:绿色 (#00ff00)
- data_frame['percentage'] 95 - 98 岁之间:琥珀色 (#ffbf00)
- data_frame['percentage'] < 95 红色 (#ff0000)
明确地说,我只需要图表中上面提到的 3 种颜色。这些颜色应根据百分比值分配。
我怎样才能做到这一点?
我认为你必须添加新的列以方便颜色匹配。请参考以下代码:
import pandas as pd
import plotly.express as px
import numpy as np
data_frame = pd.DataFrame({'region':['AA','AB','AC','AD','AE'],
'number':[2,12,6,11,30],
'percentage':[94.03,91.23,95.66,97.99,99.22]})
condition = [data_frame['percentage']>98,
(data_frame['percentage']>95)&(data_frame['percentage']<98),
data_frame['percentage']<95]
choices = ['A','B','C']
data_frame['Condition'] = np.select(condition,choices,default='D')
fig = px.treemap(data_frame, path= [data_frame['region']],
values=data_frame['number'],color=data_frame['Condition'],
color_discrete_map={'A':'#00ff00',
'B':'#ffbf00',
'C':'#ff0000',
'D':'#AB63FA'})
fig.show()
因此图表将如下所示:
我的要求是使用 python 绘制树图,我正在使用 plotly 来实现相同的... 接近我实时数据的Data frame如下
import pandas as pd
import plotly.express as px
data_frame = pd.DataFrame({'region':['AA','AB','AC','AD','AE'],
'number':[2,12,6,11,30],
'percentage':[94.03,91.23,95.66,97.99,99.22]})
下面代码中的情节看起来像这样
fig = px.treemap(data_frame, path= [data_frame['region']],
values=data_frame['number'],color=data_frame['percentage'])
fig.show()
剧情
但是,我想要基于“百分比”列的颜色编码,自定义比例如下
- data_frame['percentage'] > 98:绿色 (#00ff00)
- data_frame['percentage'] 95 - 98 岁之间:琥珀色 (#ffbf00)
- data_frame['percentage'] < 95 红色 (#ff0000)
明确地说,我只需要图表中上面提到的 3 种颜色。这些颜色应根据百分比值分配。 我怎样才能做到这一点?
我认为你必须添加新的列以方便颜色匹配。请参考以下代码:
import pandas as pd
import plotly.express as px
import numpy as np
data_frame = pd.DataFrame({'region':['AA','AB','AC','AD','AE'],
'number':[2,12,6,11,30],
'percentage':[94.03,91.23,95.66,97.99,99.22]})
condition = [data_frame['percentage']>98,
(data_frame['percentage']>95)&(data_frame['percentage']<98),
data_frame['percentage']<95]
choices = ['A','B','C']
data_frame['Condition'] = np.select(condition,choices,default='D')
fig = px.treemap(data_frame, path= [data_frame['region']],
values=data_frame['number'],color=data_frame['Condition'],
color_discrete_map={'A':'#00ff00',
'B':'#ffbf00',
'C':'#ff0000',
'D':'#AB63FA'})
fig.show()
因此图表将如下所示: