You have to establish the parent labels; it s not inherent that it s the unique values of the data in Marca
.
Here s how you get Plotly to interpret this correctly, start by creating a summary of the data to get parent container totals and parent container labels. Then you ll combine your original data with this summary. Check it out:
library(plotly)
library(tidyverse)
# summarize data frame to get parent container totals
d <- dados %>% group_by(Marca) %>% summarise(Quantidade = sum(Quantidade)) %>%
rename(Carro = Marca) %>% # change columns
mutate(Marca = "") %>% # create blank column replacement
select(names(dados)) # put columns back in order
d2 <- rbind(d, dados) %>% as.data.frame() # combine with original data
Now, when you call your plot, you ll call the data d2
. You need one more argument, as well: branchvalues
.
treemap <- plot_ly(
# data = dados,
data = d2,
type = "treemap",
labels = ~Carro,
parents = ~Marca,
values = ~Quantidade,
branchvalues = "total"
)
Here s all the code again, all together (easier copy + paste).
library(plotly)
library(tidyverse)
dados <- data.frame(
Marca = c("Chevrolet", "Chevrolet", "Chevrolet", "Chevrolet", "Chevrolet",
"Fiat", "Fiat", "Fiat", "Fiat", "Fiat", "Fiat", "Fiat", "Ford",
"Ford", "Ford", "Ford", "Ford", "Ford", "Honda", "Honda", "Hyundai",
"Hyundai", "JAC", "Renault", "Renault", "Renault", "Renault",
"Renault", "Volkswagen", "Volkswagen", "Volkswagen", "Volkswagen",
"Volkswagen", "Volkswagen"),
Carro = c("celta", "fox", "montana", "onix", "s10", "agile", "bravo", "cruze",
"punto", "siena", "strada", "uno", "ecosport", "focus", "idea", "ka",
"palio", "ranger", "city", "fit", "hb20", "tucson", "j3", "clio",
"duster", "fluence", "logan", "sandero", "crossfox", "gol", "jetta",
"polo", "saveiro", "voyage"),
Quantidade = c(483, 609, 119, 144, 117, 389, 137, 147, 397, 371, 146, 185, 93,
217, 240, 195, 134, 34, 234, 134, 149, 304, 92, 300, 186, 242,
439, 608, 132, 618, 130, 217, 75, 315)
)
# summarize data frame to get parent container totals
d <- dados %>% group_by(Marca) %>% summarise(Quantidade = sum(Quantidade)) %>%
rename(Carro = Marca) %>% # change columns
mutate(Marca = "") %>% # create blank column replacement
select(names(dados)) # put columns back in order
d2 <- rbind(d, dados) %>% as.data.frame() # combine with original data
treemap <- plot_ly(
# data = dados,
data = d2, type = "treemap", labels = ~Carro,
parents = ~Marca, values = ~Quantidade,
branchvalues = "total"
)
treemap