4
respostas

Problema no gráfico de árvore

Olá não consegui construir o gráfico de árvore. aparece o seguinte erro:

ValueError: Invalid property specified for object of type plotly.graph_objs.treemap.Marker: 'cornerradius' Estranho, pq esta parte já estava no cógigo, eu só 'descomentei'... e percebi tb que tem uma linha de código bem mais a frente na célula. Alguém pode me ajudar

Obrigada

4 respostas

Oi Mariana, tudo bem?

Para te ajudar mais assertivamente, você poderia compartilhar o seu código e o de erro em questão?

Você pode ainda compartilhar o seu notebook. Para compartilhar o seu projeto siga os passos abaixo:

  • No menu superior, no lado direito, clique em "Compartilhar".

Menu do colab,. Há dois botões "Comentário' e ' Compartilhar', está destacado em vermelho a o botão Compartilhar

  • Em seguida, em acesso geral, clique no modo leitor.

Captura de tela do colab. Há um texto 'Acesso Geral', abaixo há um texto 'qualquer pessoa com o link' . Ao alado está destacado em vermelho a opção leitor

Fico no aguardo.

Fico no aguardo e à disposição

Olá Monalisa,

Obrigada por responder! Vou mandar o meu código numa resposta e o erro em outra pq não cabe a qui. Meu código é esse:

Criando um df com os dados desejados

pib_2020 = df_pib.copy() pib_2020 = pib_2020.query("ano == 2020")[["regiao", "sigla_uf", "pib"]]

Ajustando os valores do PIB para bilhões e ordenando pelo pib

pib_2020['pib'] = (pib_2020['pib'] / 1e9).round(0).astype('int64') pib_2020 = pib_2020.sort_values('pib', ascending = False)

Gerando uma coluna para a porcentagem da representação de cada estado no PIB de 2020

e passando para 0 a 100 %

pib_2020['pib_%'] = pib_2020['pib'].div(pib_2020['pib'].sum(), axis = 0) pib_2020['pib_%'] = (pib_2020['pib_%'] * 100).round(1) pib_2020.head()

Importando a biblioteca

import plotly.express as px

Gerando o gráfico de árvore (TREEMAP) para os anos de 2015 a 2022

fig = px.treemap(pib_2020, path = [px.Constant('Distribuição do PIB'), 'sigla_uf'], values = 'pib_%', color = 'regiao', custom_data = ['regiao', 'pib'], title = 'Distribuição do PIB nos estados brasileiros no ano de 2020 (em bilhões de reais)', color_discrete_map = {'(?)': BRANCO, 'Sudeste': AZUL3, 'Sul': LARANJA1, 'Nordeste': AZUL5, 'Centro-Oeste': VERDE1, 'Norte': CINZA5})

Ajustando o layout do gráfico

fig.update_layout(width=1400, height=600, margin = dict(t=50, l=0, r=0, b=25), font_family = 'DejaVu Sans', font_size=14, font_color= CINZA2, title_font_color= CINZA1, title_font_size=24)

Ajustando o hovertext

fig.update_traces(marker=dict(cornerradius=3), texttemplate='%{label}', hovertemplate='Estado: %{label} Região = %{customdata[0]} ' 'PIB = R$ %{customdata[1]} bi (%{value}%)') fig.show()

E o erro que está acontecendo é este:


ValueError Traceback (most recent call last) Cell In[27], line 16 12 fig.update_layout(width=1400, height=600, margin = dict(t=50, l=0, r=0, b=25), font_family = 'DejaVu Sans', 13 font_size=14, font_color= CINZA2, title_font_color= CINZA1, title_font_size=24) 15 # Ajustando o hovertext ---> 16 fig.update_traces(marker=dict(cornerradius=3), texttemplate='%{label}', 17 hovertemplate='Estado: %{label} Região = %{customdata[0]} ' 18 'PIB = R$ %{customdata[1]} bi (%{value}%)') 19 fig.show()

File ~/anaconda3/lib/python3.11/site-packages/plotly/graph_objs/_figure.py:710, in Figure.update_traces(self, patch, selector, row, col, secondary_y, overwrite, **kwargs) 647 def update_traces( 648 self, 649 patch=None, (...) 655 **kwargs, 656 ) -> "Figure": 657 """ 658 659 Perform a property update operation on all traces that satisfy the (...) 708 709 """ --> 710 return super(Figure, self).update_traces( 711 patch, selector, row, col, secondary_y, overwrite, **kwargs 712 )

File ~/anaconda3/lib/python3.11/site-packages/plotly/basedatatypes.py:1374, in BaseFigure.update_traces(self, patch, selector, row, col, secondary_y, overwrite, **kwargs) 1320 """ 1321 Perform a property update operation on all traces that satisfy the 1322 specified selection criteria (...) 1369 Returns the Figure object that the method was called on 1370 """ 1371 for trace in self.select_traces( 1372 selector=selector, row=row, col=col, secondary_y=secondary_y 1373 ): -> 1374 trace.update(patch, overwrite=overwrite, **kwargs) 1375 return self

File ~/anaconda3/lib/python3.11/site-packages/plotly/basedatatypes.py:5122, in BasePlotlyType.update(self, dict1, overwrite, **kwargs) 5120 with self.figure.batch_update(): 5121 BaseFigure._perform_update(self, dict1, overwrite=overwrite) -> 5122 BaseFigure._perform_update(self, kwargs, overwrite=overwrite) 5123 else: 5124 BaseFigure._perform_update(self, dict1, overwrite=overwrite)

File ~/anaconda3/lib/python3.11/site-packages/plotly/basedatatypes.py:3908, in BaseFigure._perform_update(plotly_obj, update_obj, overwrite) 3902 validator = plotly_obj._get_prop_validator(key) 3904 if isinstance(validator, CompoundValidator) and isinstance(val, dict): 3905 3906 # Update compound objects recursively 3907 # plotly_obj[key].update(val) -> 3908 BaseFigure._perform_update(plotly_obj[key], val) 3909 elif isinstance(validator, CompoundArrayValidator): 3910 if plotly_obj[key]: 3911 # plotly_obj has an existing non-empty array for key 3912 # In this case we merge val into the existing elements

File ~/anaconda3/lib/python3.11/site-packages/plotly/basedatatypes.py:3885, in BaseFigure._perform_update(plotly_obj, update_obj, overwrite) 3881 continue 3882 # If no match, raise the error, which should already 3883 # contain the _raise_on_invalid_property_error 3884 # generated message -> 3885 raise err 3887 # Convert update_obj to dict 3888 # -------------------------- 3889 if isinstance(update_obj, BasePlotlyType):

ValueError: Invalid property specified for object of type plotly.graph_objs.treemap.Marker: 'cornerradius'

Did you mean "coloraxis"?

Valid properties: autocolorscale Determines whether the colorscale is a default palette (autocolorscale: true) or the palette determined by marker.colorscale. Has an effect only if colors is set to a numerical array. In case colorscale is unspecified or autocolorscale is true, the default palette will be chosen according to whether numbers in the color array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here colors) or the bounds set in marker.cmin and marker.cmax Has an effect only if colors is set to a numerical array. Defaults to false when marker.cmin and marker.cmax are set by the user. cmax Sets the upper bound of the color domain. Has an effect only if colors is set to a numerical array. Value should have the same units as colors and if set, marker.cmin must be set as well. cmid Sets the mid-point of the color domain by scaling marker.cmin and/or marker.cmax to be equidistant to this point. Has an effect only if colors is set to a numerical array. Value should have the same units as colors. Has no effect when marker.cauto is false. cmin Sets the lower bound of the color domain. Has an effect only if colors is set to a numerical array. Value should have the same units as colors and if set, marker.cmax must be set as well. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under layout.coloraxis, layout.coloraxis2, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:plotly.graph_objects.treemap.marker.ColorBar instance or dict with compatible properties colors Sets the color of each sector of this trace. If not specified, the default trace color set is used to pick the sector colors. colorscale Sets the colorscale. Has an effect only if colors is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, [[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]. To control the bounds of the colorscale in color space, use marker.cmin and marker.cmax. Alternatively, colorscale may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,E lectric,Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd Bu,Reds,Viridis,YlGnBu,YlOrRd. colorssrc Sets the source reference on Chart Studio Cloud for colors. depthfade Determines if the sector colors are faded towards the background from the leaves up to the headers. This option is unavailable when a colorscale is present, defaults to false when marker.colors is set, but otherwise defaults to true. When set to "reversed", the fading direction is inverted, that is the top elements within hierarchy are drawn with fully saturated colors while the leaves are faded towards the background color. line :class:plotly.graph_objects.treemap.marker.Line instance or dict with compatible properties pad :class:plotly.graph_objects.treemap.marker.Pad instance or dict with compatible properties reversescale Reverses the color mapping if true. Has an effect only if colors is set to a numerical array. If true, marker.cmin will correspond to the last color in the array and marker.cmax will correspond to the first color. showscale Determines whether or not a colorbar is displayed for this trace. Has an effect only if colors is set to a numerical array.

Did you mean "coloraxis"?

Bad property path: cornerradius ^^^^^^^^^^^^

Eu estou utilizando o jupyter.