结合barplot和grid.table

时间:2017-01-17 14:49:40

标签: r gridextra

# 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)

enter image description here

enter image description here

另一种选择是将条形图转换为ggplot geom_bar,但我努力做到超过2列。

2 个答案:

答案 0 :(得分:4)

这是使用addtable2plot plotrix个软件包执行此操作的一种方法。它允许您使用图例位置,例如"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)

enter image description here

答案 1 :(得分:2)

如果您想在<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="" id=""> <option value="normal">Normal</option> <option value="special">Special</option> </select> <p><span id="add_dollar"> 5000 </span> dollar</p>中制作条形图,则需要将数据重新整形为长格式。根据您的示例数据,以下代码:

ggplot2

得出以下结果:

enter image description here