如何解决Plotly:如何在 plotly.graph_objects (Pie & Bar) 中通过变量/标签定义颜色
我是 plotly 的新手,我在下面有两个不同的图 (go.Pie & go.Bar),我喜欢为每种类型 (a: g) 标签分配一种颜色,如 color_discrete_map 中所示。我如何将它们包含在 go.pie 和 go.bar 的代码中?谢谢
MB<-st_read("Export_Output_4.shp")
#checking first 6 lines of data
> head(MB)
Simple feature collection with 6 features and 0 fields
geometry type: POINT
dimension: XY
bBox: xmin: -118.8032 ymin: 62.69849 xmax: -118.7922 ymax: 62.70768
geographic CRS: WGS 84
geometry
1 POINT (-118.7922 62.69849)
2 POINT (-118.7992 62.7012)
3 POINT (-118.7989 62.70186)
4 POINT (-118.7992 62.70115)
5 POINT (-118.7949 62.70768)
6 POINT (-118.8032 62.70574)
解决方法
对于 unit_mix_pie
和 unit_mix_bar
是只有一行和一列的子图,我有点困惑 - 您可以将这些对象中的每一个定义为 plotly graph_object 或 plotly express图。
如果您使用 plotly express 定义 unit_mix_pie
,您可以直接将您的 color_discrete_map
作为参数传递:
import pandas as pd
import plotly.express as px
df = pd.DataFrame(data={'type':list('abcdefg'),'no':[50,100,200,300,400,500,600]})
## added another color for the type 'g'
color_discrete_map = {'a':'rgb(42,9,4)','b':'rgb(111,203,209)','c':'rgb(55,165,172)','d':'rgb(29,127,136)','e':'rgb(2,84,92)','f':'rgb(4,37,42)','g':'purple'}
unit_mix_pie = px.pie(df,values='no',names='type',color='type',color_discrete_map=color_discrete_map)
unit_mix_pie.show()
然后你可以将 unit_mix_bar
定义为一个 plotly graph_object 来单独添加条形使用轨迹,将它们的类型映射到它们的颜色(我从 vestland's answer to a similar question 借用):
import plotly.graph_objects as go
## add the bars one at a time
unit_mix_bar=go.Figure()
for t in df['type'].unique():
dfp = df[df['type']==t]
unit_mix_bar.add_traces(go.Bar(x=dfp['no'],y = dfp['type'],name=t,marker_color=color_discrete_map[t]))
unit_mix_bar.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。