Automatically resizing legend for a plot made using ggplot2 such that the entire legend lies within the boundary of the layer

StackOverflow https://stackoverflow.com/questions/21339138

Pergunta

I have some data here

I read the data into a data frame and then plot this data with this following code,

# Reading data from a .csv file into a data frame
     df <- read.table("newcsv_file.csv",header=T,sep="\t" )
# Now melting the data frame prior to plotting     
df_mlt <- melt(df, id=names(df)[1], measure=names(df)[c(2, 6, 11,16,21,26,31,36,41,46,51,106,111,116,121,126,131,136,141,146,151)], variable = "cols")

# plotting the data
plt_fit <- ggplot(df_mlt, aes(x=x,y= value, color=cols)) +
    geom_point(size=2) +
    geom_smooth(method = "lm", se = FALSE) +
    scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", math_format(10^.x))) +
    annotation_logticks(sides = "rl") +
    theme_bw() + 
    theme(legend.text=element_text(size=12), legend.title=element_text(size=12))+
    theme(axis.text=element_text(size=14)) +
    theme(axis.title=element_text(size=14,face="bold")) +
    labs(x = "x", y = "y") +
    scale_color_discrete(name = "values", labels = c("0","-0.1","-0.2","-0.3","-0.4","-0.5","-0.6","-0.7","-0.8","-0.9","-1","+0.1","+0.2","+0.3","+0.4","+0.5","+0.6","+0.7","+0.8","+0.9","+1")) +
    guides(colour = guide_legend(override.aes = list(size=3),nrow=2,title.position = 'top',title.hjust=0.5,legend.direction = "horizontal")) +
    theme(legend.position = 'bottom', legend.margin=unit(1,"cm"),legend.background = element_rect(fill ='gray94')) +
    theme(plot.margin=unit(c(0,2,0,0),"mm"))

The resulting plot looks like this, the problem here is that the right most edge of the legend is cropped.

enter image description here

I use +theme(legend.margin=unit(1,"cm")) but this does not seem sufficient. Could someone please let me know what I can change to display the full legend properly in the plot.

Thanks.

Foi útil?

Solução 2

After changing the width and height of the plot using the following code,

ggsave(file="new_png_file.png",width=22,height=21,units=c("cm"), dpi=600)

Yields a plot such as this,

enter image description here

Outras dicas

The code is fine. The problem is the size of your plot window. Try making it wider and you'll see the whole legend.

Also,

ggsave("plot_fit.pdf",plot_fit)

will create a pdf where the full legend is displayed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top