Reputation: 403
I wanted to make a barplot like the figure a of this one that I found in a publication with something like a table tab showing some information outside the plot using ggplot
. I found this general approach of adding text outside of a plot using gridExtra
.
However, my question is how to align the height of each row of the table tab to each bar of the barplot so they match?
Here is an example. I wanted to add the note
as a table tab on the right of the barplot.
library(ggplot2)
library(gridExtra)
df <- data.frame(Model = c("Datsun 710","Duster 360","Hornet 4 Drive","Hornet
Sportabout","Mazda RX4 Wag","Merc 230","Merc 240D","Valiant"),
logFC = c(1.879,1.552,1.360,1.108,-2.407,-2.416,-2.670,-3.061),
Note = c("ModelA","ModelB","ModelC","ModelD","ModelE","ModelF","ModelG","ModelH"))
plot <- ggplot(df, aes(Model, logFC)) +
geom_bar(stat="identity") +
coord_flip() +
theme_bw() +
ggtitle("Data for cars") +
theme(plot.title = element_text(size = 18, hjust = 0.5))
tab <- as.data.frame(
c(Note = df$Note))
rownames(tab) <- NULL
p_tab <- tableGrob(unname(tab))
grid.arrange(plot, p_tab, ncol = 2)
Upvotes: 2
Views: 137
Reputation: 403
Per Gregor's comment, this works for me:
plot <- ggplot(df, aes(Model, logFC, label=Note)) +
geom_bar(stat="identity") +
coord_flip(clip = "off") +
theme_bw() +
ggtitle("Data for cars") +
theme(plot.title = element_text(size = 18, hjust = 0.5))+
geom_text(y = 3,
hjust = 0,
size = 5) +
theme(plot.margin = unit(c(1,10,1,1), "lines"),
panel.border=element_blank(),
axis.line = element_line(),
panel.grid.major=element_blank(),
panel.grid.minor = element_blank())
Upvotes: 1