I'm working with ggplot and treemapify to generate a treemap.
The problem is that some blocks are too small so i can't put text inside of them. I've been trying to use scale_fill_manual
in order to generate some legends outside the graph by breaks
argument but it comes with two problems. If I only specify the labels that I want, the other ones turn green and I can't change their fill collor. On the other hand, when I use all the labels it shows them all.
How can I choose which legends I want to show in the graph?
This is the resulting treemap when I try to add the legends with all labels
This is the resulting treemap when I try to add the legends with the labels that I want
This is the code I'm currently working on:
ggplot(TM_df, aes(label = Labels, area = Values, fill = Labels))
geom_treemap()
geom_treemap_text(fontface = "bold", colour = "white", place = "centre")
scale_fill_manual("", breaks = TM_df$Labels,
values = colores, drop = F)
theme(
legend.title = element_blank(),
legend.position = "bottom"
)
And this is my dataset:
TM_df <- data.frame( Labels = c("Servicios Personales\n10,643 mdp (-5.1%)",
"Materiales y Suministros\n1,597 mdp ( 16.1%)", "Servicios Generales\n2,346 mdp (-25.0%)",
"Transferencias, Asignaciones,\nSubsidios y Otras Ayudas\n44,212 mdp ( 8.8%)",
"Bienes Muebles, Inmuebles e Intangibles\n112 mdp (-55.8%)",
"Inversion Publica\n1,336 mdp (-29.3%)",
"Inversiones Financieras\ny Otras Provisiones\n48 mdp (-35.2%)",
"Deuda Publica\n8,977 mdp ( 25.7%)"),
Values = c(10643.28124, 1596.93410, 2346.43756, 44211.92169, 112.46303,
1335.76290, 48.30434, 12080.91506, 8976.59709))
CodePudding user response:
One option to prevent the fill colors to be removed when setting the breaks would be to make use of a named vector which assigns colors to category names:
library(treemapify)
library(ggplot2)
colores <- scales::brewer_pal(palette = "Dark2")(8)
ggplot(TM_df, aes(label = Labels, area = Values, fill = Labels))
geom_treemap()
geom_treemap_text(fontface = "bold", colour = "white", place = "centre")
scale_fill_manual("",
breaks = TM_df$Labels[c(5, 7)],
values = setNames(colores, TM_df$Labels)
)
theme(
legend.title = element_blank(),
legend.position = "bottom"
)