Reputation: 1797
I want to create nice confidence interval plot for my data frame df
:
> df
Estimate Lower Upper
A1 0.005414976 -0.01227699 0.02310694
A2 0.004046546 -0.01368911 0.02178220
A3 0.002761602 -0.01491484 0.02043804
A4 -0.002860038 -0.02049349 0.01477342
A5 -0.004197288 -0.02178773 0.01339316
A6 0.011004835 -0.12687561 0.14888529
B1 -0.001077768 -0.01130327 0.00914773
C1 0.137894575 -0.09659997 0.37238912
D1 0.128514414 -0.10866480 0.36569363
D2 0.168863152 -0.06347553 0.40120183
D3 0.139645665 -0.09431216 0.37360349
D4 0.028744139 -0.19562867 0.25311695
As can be seen from data set, first 6 rows represent levels of one factor, then there are two factors with only one level and the last is factor with 4 levels. I would like to display it in such a way to be clear that levels belong to one factor.
My current plot looks like this:
ggplot(df, aes(x = rownames(df), y = Estimate, ymin = Lower, ymax = Upper)) +
geom_pointrange() +
geom_hline(yintercept = 0, linetype = 2) +
coord_flip()
The desired output should look like this:
I know there is another option how to group factors, e.g. see this, but I would like to create something as described.
Any help would be much appreciated!
Upvotes: 2
Views: 1215
Reputation: 98419
One solution (using version 2.2.0 of ggplot2
) is to use the faceting but adjusting position to the same side as axis and then putting facet names outside the axis and changing text direction and vertical position.
First, added new variable to show factor levels.
df$Level <- paste("Factor ",substr(rownames(df),1,1))
ggplot(df, aes(x = rownames(df), y = Estimate, ymin = Lower, ymax = Upper)) +
geom_pointrange() +
geom_hline(yintercept = 0, linetype = 2) +
coord_flip() +
facet_grid(Level~.,scales = "free",space="free",switch = "both") +
theme(strip.placement = "outside",
strip.text.y = element_text(angle = 180,vjust=1, face = "bold"),
strip.background = element_blank(),
panel.spacing = unit(0,"cm"))
Upvotes: 5