Matteo Castagna Matteo Castagna - 2 months ago 19
R Question

R ggplot2 facet_grid scales and space

There are few threads dealing with similar issues but I really didn't manage to get this one to work as I would expect it to.

I have this dataset:

Item AssetClass variable value
89 F/EER Hybrids 2016-09-15 5.0014
103 F/SOLG MA 2016-09-15 1.5829
104 F/SOP MA 2016-09-15 -5.4365
105 F/SRV MA 2016-09-15 6.1000
49 F/EER Hybrids 2016-06-15 0.7179
63 F/SOLG MA 2016-06-15 0.0000
64 F/SOP MA 2016-06-15 4.7124
65 F/SRV MA 2016-06-15 13.5132
9 F/EER Hybrids 2016-03-15 0.9599
23 F/SOLG MA 2016-03-15 0.0000
24 F/SOP MA 2016-03-15 6.6873
25 F/SRV MA 2016-03-15 9.9191


with the following structure:

'data.frame': 12 obs. of 4 variables:
$ Item : Factor w/ 40 levels "BRITISH POUND",..: 32 22 2 35 32 22 2 35 32 22 ...
$ AssetClass: chr "Hybrids" "MA" "MA" "MA" ...
$ variable : Date, format: "2016-09-15" "2016-09-15" ...
$ value : num 5.001 1.583 -5.436 6.1 0.718 ...


I am trying to plot those data using:

ggplot(chartSet, aes(x = Item,
y = value,
alpha = factor(variable))) +
geom_bar(stat = "identity", position = "dodge", fill = "red") +
scale_alpha_manual(values = c(0.1, 0.4, 1)) +
labs(alpha = "") +
theme_bw() + xlab("") + ylab("% Contribution to VaR") +
facet_grid(AssetClass ~ ., scales = "free_x", space = "free_x") +
coord_flip() +
theme(strip.text.y = element_text(angle = 0)) +
theme(legend.position = "bottom",
axis.text = element_text(size = 5))


This is something I do with other type of geoms and dataset but I really do not understand why this time I have this output:

Current output

What I would like to have instead is only F/EER in the Hybrids facet and the other three in the MA one. Given I am using "free_x" for scales this is what I was expecting.

Using the full set of data this is an example of "success":

Good output

There is a fair chance I am getting lost in a glass of water; if that is the case: sorry!

Answer

The problem here, as often with facetting, is the combination of coord_flip with anything more than the most basic facets. And as usual, the problem can be solved using the ggstance package on github. This package has horizontal versions of common geoms, such as geom_barh, which make coord_flip unnecessary.

library(ggstance)
ggplot(chartSet, aes(y = Item, 
                     x = value, 
                     alpha = factor(variable))) +
         geom_barh(stat = "identity", position = "dodge", fill = "red") + 
         scale_alpha_manual(values = c(0.1, 0.4, 1)) +
         labs(alpha = "") +
         theme_bw() + ylab("") + xlab("% Contribution to VaR") +
         facet_grid(AssetClass ~ ., scales = "free_y", space = "free_y") +
         theme(strip.text.y = element_text(angle = 0)) +
         theme(legend.position = "bottom",
               axis.text = element_text(size = 5))

enter image description here

Comments