Question

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)
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top