将标签放置在沿着x轴的R中的图中

时间:2016-08-05 05:31:43

标签: r plot label

我在R中绘制了一个图,现在我想沿着图的x轴放置标签。我想将标签放在属于特定人群的样本数量的中心。如果我有5个样本大小为10,20,20,35,100的群体,则群体1的标签应为10/2,群体2为20/2,依此类推。我尝试了以下但它不起作用。感谢任何进一步的帮助! 我输入文件的样本(input.5.Q,只显示5个样本。实际上它包含185行和5列)

1   0.364957    0.00001 1.00E-05    0.00001 1.00E-05
2   0.485423    0.017426    1.00E-05    0.00001 1.00E-05
3   0.399289    0.00001 1.00E-05    0.002894    1.00E-05
4   0.579652    0.00001 1.00E-05    0.00001 1.00E-05
5   0.578574    0.00001 1.00E-05    0.00001 1.00E-05
6   0.597478    0.00001 1.00E-05    0.00001 1.00E-05

tbl<-read.table(input.5.Q)    
pop<-c("pop1", "pop2", "pop3", "pop4", "pop5")
    n<-c(10, 20,20,35,100)
    at <- n/2
    barplot(t(as.matrix(tbl)),col=rainbow(5),width=1,space=1)
    mtext(1,at=at,text=pop,cex=1, las=2)
    for{....
    }

2 个答案:

答案 0 :(得分:0)

您可以尝试:

tbl <- read.table("clipboard", row.names= NULL) # read your data
head(tbl)
V1       V2       V3    V4       V5    V6
1  1 0.364957 0.000010 1e-05 0.000010 1e-05
2  2 0.485423 0.017426 1e-05 0.000010 1e-05
3  3 0.399289 0.000010 1e-05 0.002894 1e-05
4  4 0.579652 0.000010 1e-05 0.000010 1e-05
5  5 0.578574 0.000010 1e-05 0.000010 1e-05
6  6 0.597478 0.000010 1e-05 0.000010 1e-05
# the barplot
colnames(tbl)[-1] <-c("pop1", "pop2", "pop3", "pop4", "pop5")
barplot(as.matrix(tbl[,-1]),beside = T)

enter image description here

答案 1 :(得分:0)

例如,您可以尝试这样的事情(它不是您想要的,但可能足够接近?):

# example data
tbl <- data.frame(population = c(rep("pop1", 10), rep(c("pop2", "pop3"), each = 20), rep("pop4", 35), rep("pop5", 100)), 
              V1 = seq(0, 1, size = 185, replace = TRUE),
              V2 = seq(0, 0.1, size = 185, replace = TRUE),
              V3 = seq(1e-05, 0, size = 185, replace = TRUE),
              V4 = seq(0, 0.01, size = 185, replace = TRUE),
              V5 = seq(1e-05, 0, size = 185, replace = TRUE))


library(gridExtra)
library(grid)
library(ggplot2)
library(lattice)

我为绘图创建了一个函数,以便更容易单独绘制每个变量。我也尝试将所有变量都放在一个图中,但这样做不太好 - 太乱了

plot_func <- function(column){
  ggplot(data = tbl, aes_string(x = 1:nrow(tbl), y = column, fill = "population")) + 
    geom_bar(stat = "identity") + 
    theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank()) +
    theme(legend.title = element_blank(), legend.position = "bottom")
}

# run the plot function for each variable and plot
for (i in 2:ncol(tbl)){
  assign(paste("p", i-1, sep = ""), plot_func(column = paste0(colnames(tbl)[i])))
}

grid.arrange(p1, p2, p3, p4, p5, ncol=2)

enter image description here