结合条形图和 grid.table

combine barplot and grid.table

# I am trying to combine a horizontal beside barplot with the table
# with the values in it.

# E.g. original table, including sample_ids

df = data.frame(
  sample_id=c("s01","s02","s03","s04","s05","s06","s07","s08","s09","s10"),
  one=runif(10,0,10),
  two=runif(10,0,10),
  three=runif(10,0,10),
  four=runif(10,0,10)
)

# I created a mydata that I then do barplot as matrix

mydata = data.frame(
  one=df$one,
  two=df$two,
  three=df$three,
  four=df$four
)

# Plotted, using rainbow colouring, with a legend in the top right

barplot(as.matrix(mydata),horiz=TRUE,beside=TRUE,col=rainbow(length(df$sample_id)), legend=paste(df$sample_id), args.legend = list(x = "topright", bty = "n"),xlim=c(0,20))

# Now I would like the grid.table to be on the bottom right, ideally with the same order and colouring as the legend

library(gridExtra)
grid.table(df)

# Any ideas?


# EDIT: also tried addtable2plot from plotrix, with no much success

bp = barplot(as.matrix(mydata),horiz=TRUE,beside=TRUE,col=rainbow(length(df$sample_id)), legend=paste(df$sample_id), args.legend = list(x = "topright", bty = "n"),xlim=c(0,20))

library(plotrix)
addtable2plot(bp, y=0, df,cex=0.3)

另一种选择是将 barplot 变成 ggplot geom_bar,但我很难做到超过 2 列。

这是使用 plotrix 包的 addtable2plot 的一种方法。它允许您使用图例位置,例如 "bottomright"

df = data.frame(
  sample_id=c("s01","s02","s03","s04","s05","s06","s07","s08","s09","s10"),
  one=runif(10,0,10),
  two=runif(10,0,10),
  three=runif(10,0,10),
  four=runif(10,0,10)
)

mydata = data.frame(
  one=df$one,
  two=df$two,
  three=df$three,
  four=df$four
)

library(plotrix)
dev.off()
windows(width = 8, height = 6)
df$one = round(df$one,2)
df$two = round(df$two,2)
df$three = round(df$three,2)
df$four = round(df$four,2)
barplot(as.matrix(mydata),horiz=TRUE,beside=TRUE,col=rainbow(length(df$sample_id)),
                  legend=paste(df$sample_id),
                  args.legend = list(x = "topright", bty = "n", cex = 1),
                  xlim=c(0,20))
addtable2plot("bottomright",table = df, cex = .9, bty = "o",
              bg = c("white","grey"), vlines = TRUE, xpad = .25)

如果您想在 ggplot2 中制作条形图,您需要将数据重塑为长格式。根据您的示例数据,以下代码:

library(ggplot2)
library(gridExtra)
library(reshape2)

bp <- ggplot(melt(df, id.vars = 1),
             aes(x = variable, y = value, fill = sample_id)) +
  geom_bar(stat = 'identity', position = 'dodge') +
  scale_fill_manual(values = rainbow(10)) +
  labs(x = NULL, y = NULL) +
  coord_flip() +
  theme_minimal(base_size = 14)
gt <- tableGrob(df, rows = NULL, theme = ttheme_minimal())

grid.arrange(bp, gt, ncol = 2, widths = c(2.5,2))

结果如下: