Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand plotting area by x-axis to make room for direct labels

I am polishing my graphs and have a problem with fitting direct labels in the plotting area. A want to remove most of the area between y1 and the y-axis to the left in the plot similar to that generated by the code below, but keep the extra area to the right to have room for the labels.

Adding +scale_x_discrete(expand=c(0,0.05)) removes extra area on both sides, but leaves no room for labels, and it can't seem to remove it on only one side.

Adding margins to the right of the plotting area with +theme(plot.margin = unit(c(0,4,0,0), "cm")) still doesn't allow the labels to appear there.

A solution that places the labels outside, to the right of the border would be even better.

Any help much appreciated.

library(ggplot2)
library(directlabels)
library(reshape2)
theme_set(theme_bw())
# some data
dfr<-data.frame(c("Longish Name A","Longish Name B","Longish Name C"),c(1,1,1),c(1,2,3),c(2,3,4)) 
colnames(dfr) <- c("subject","y1","y2","y3")
dfr<-melt(dfr, id.vars="subject")
# the graph
ggplot(data=dfr,aes(y=value, x=variable, group=subject)) +
geom_line(aes(color=subject))+
geom_dl(aes(label=subject), list(dl.trans(x=x+0.2), "last.qp", cex=0.5)) +
guides(color=FALSE)
like image 673
Andreas Avatar asked Jan 18 '14 19:01

Andreas


People also ask

How do I extend the X-axis labels in R?

To set labels for X and Y axes in R plot, call plot() function and along with the data to be plot, pass required string values for the X and Y axes labels to the “xlab” and “ylab” parameters respectively. By default X-axis label is set to “x”, and Y-axis label is set to “y”.

How do I reduce the size of X-axis labels in R?

Go to the menu in RStudio and click on Tools and then Global Options. Select the Appearance tab on the left. Again buried in the middle of things is the font size. Change this to 14 or 16 to start with and see what it looks like.


1 Answers

Convert your x values to numeric inside the aes() and then use scale_x_continuous() to get back to original labels and set limits= that are wider on side.

ggplot(data=dfr,aes(y=value, x=as.numeric(variable), group=subject)) +
  geom_line(aes(color=subject))+
  geom_dl(aes(label=subject), list(dl.trans(x=x+0.2), "last.qp", cex=0.5)) +
  guides(color=FALSE)+
  scale_x_continuous(breaks=c(1,2,3),labels=c("y1","y2","y3"),expand=c(0,0.05),
                     limits=c(1,3.4))

enter image description here

like image 171
Didzis Elferts Avatar answered Sep 19 '22 13:09

Didzis Elferts