2015-12-04 2 views
1

вот мой текущий код:добавить текст в правую часть барной стойки

vec2<- c(10.810811, 18.146718, 25.096525, 26.640927, 16.216216, 3.088803) 
b<-barplot(as.matrix(vec2), ylab = "Total Percentage", xlab="studies", col = c("red", "yellow", "green", "violet", "skyblue", "cyan"), width=1) 
# Find the top y position of each block 
ypos <- apply(as.matrix(vec2), 2, cumsum) 
# Move it downwards half the size of each block 
ypos1 <- ypos - vec2/2 
ypos1 <- t(ypos1) 
text(b, ypos1, labels=round(vec2)) 

используя мой текущий код, как добавить текст к этому barplot на праве за пределами цветовых закодированы частями участка? Мне нужен текст посередине и снаружи справа от сюжета? Также, как мне сделать скин-сет?

+0

Вы посмотрели на '? mtext'? –

+0

У меня есть и не совсем понятно, как mtext отличается от текста. – Genetics

+1

Он предназначен для записи на полях. Подожди. вам также нужно прочитать '? par' ... особенно параметр' mar', а также 'xpd'. –

ответ

2

В последнее время я столкнулся с аналогичной ситуацией. Я думаю, что мое решение должно быть применимо и к вашей ситуации. Я выполнил это с помощью функции layout(), чтобы создать многопанельный график, в котором legend() был помещен в узкую пустую панель.

Важной частью кода я использовал это следующим образом

##################### 
# Set up the plots 

BARPLOT_COLORS<-c("blue","purple","red") 

# setup the matrix for the plot layout 
# it is easier to create this in a csv file in Excel, etc., then read it into R as a matrix 
# here is the dput() code for the matrix I made 
Counts_matrix<-structure(c(1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 2L, 
            2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 
            3L, 3L, 3L, 3L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), 
            .Dim = c(11L,4L), 
            .Dimnames = list(NULL, c("V1", "V2", "V3", "V4"))) 
# looks like this 
# > Counts_matrix 
# V1 V2 V3 V4 
# [1,] 1 1 1 1 
# [2,] 2 2 2 2 
# [3,] 2 2 2 2 
# [4,] 2 2 2 2 
# [5,] 2 2 2 2 
# [6,] 2 2 2 2 
# [7,] 3 3 3 3 
# [8,] 3 3 3 3 
# [9,] 3 3 3 3 
# [10,] 3 3 3 3 
# [11,] 3 3 3 3 
# the numbers here correspond to contiguous areas in which the plots will be placed 
# in the numerical order specified 
# since the OP wants the legend on the right side, make a matrix like this with 1's along that side 


# setup the panel layout by passing the matrix to layout() 
layout(Counts_matrix) 
# layout.show(max(Counts_matrix)) # use this to preview the layout 

par(mar=c(0,0,4,0)) # need to set this for some reason 
# on mar: A numerical vector of the form c(bottom, left, top, right) which gives the number of lines of margin to be specified on the four sides of the plot. 
# The default is c(5, 4, 4, 2) + 0.1. 

# call blank plot to fill the first panel 
plot(1,type='n',axes=FALSE,xlab="",ylab="",main = "Quality Counts",cex.main=2) 

# set up the Legend in the first panel 
legend("bottom",legend=c("Good","Bad","Ugly"),fill=BARPLOT_COLORS,bty = "n",ncol=length(BARPLOT_COLORS),cex=1.0) 

# set the mar for the remaining panels 
par(mar=c(6,5,0,4)) 
# create barplot for the two matrices 
barplot(Raw_Counts,horiz = T,col=BARPLOT_COLORS,border=NA,las=1,cex.names=1,xlab="Number of counts (millions)") 
barplot(Pcnt_Counts,horiz = T,col=BARPLOT_COLORS,border=NA,las=1,cex.names=1,xlab="Percent of counts") 

Я сделал много читать, чтобы понять это; некоторые соответствующие ссылки можно найти здесь:

http://seananderson.ca/courses/11-multipanel/multipanel.pdf

Common legend for multiple plots in R

Весь код, который я использовал, можно найти здесь:

https://github.com/stevekm/Bioinformatics/blob/master/scripts/alignment_summary_muti_panel_barplot.R

Вы должны иметь возможность копировать/вставить что прямо в RStudio и запустите его, чтобы увидеть, как он работает

+0

Это работает как шарм. Спасибо за великолепные – Genetics

1

Если вы не хотите устанавливать какие-либо пакеты, вы можете сделать следующее ...

текст (х = 1,25, у = 50, лейблы = "Здесь идет текст", SRT = 270, XPD = T)

х определяет смещение в х
у определяет смещение в у
меток, что вы хотите, чтобы отобразить
SRT задает угол, который прикладывается к нему (90 щелкнет, что я отправил)
xpd позволяет передавать текст за пределы границы (попробуйте это как False, чтобы увидеть, что я говорю)

+0

Этот способ также работает. Благодаря! – Genetics