steve steve - 3 months ago 28
R Question

ggplot2 - Change legend/variable names and remove blank space in x axis

I have the following data:

DAYS;GWFDisi;GSWIM;GGAP3;GHYPE;GVIC;HWFDisi;HSWIM;HGAP3;HHYPE;HVIC;IWFDisi
1;-308.78;-183.19;-232.48;-233.22;-150.38;-596.49;-311.58;-571.41;-387.63;-315.43;-451.26
2;-348.52;-192.39;-314.68;-231.67;-147.88;-563.14;-335.39;-558.46;-423.13;-355.14;-501.58
3;-416.24;-211.68;-436.83;-232.73;-164.87;-537.54;-327.19;-465.70;-455.62;-403.40;-458.43
4;-459.95;-217.75;-486.37;-228.07;-202.23;-560.68;-359.07;-497.20;-481.41;-430.87;-475.76
5;-437.58;-219.63;-494.34;-223.27;-249.18;-613.41;-371.47;-457.38;-499.42;-433.01;-446.02
6;-470.20;-228.91;-503.95;-217.41;-292.13;-618.50;-381.87;-505.86;-505.63;-430.23;-440.30
7;-500.54;-245.91;-527.91;-226.86;-319.97;-599.95;-381.06;-416.05;-474.56;-431.76;-526.32


I am plotting this data using the following code:

rm(list = ls())
setwd("C:/Users/stevens/Desktop/daily_days")
almourol_diff <- read.table("data.csv", header = TRUE, sep = ";", fill = TRUE)
library(ggplot2)
library(reshape2)
data <- melt(data, id.vars="DAYS")
png("data.png", width = 600, height = 400)
p <- ggplot(data, aes(DAYS,value, col=variable))
p + geom_line(size = 0.1) +
geom_hline(aes(yintercept = 0), linetype="dotted") +
ylab("Diff in runoff [m3/s]") +
theme_bw() +
theme(legend.key = element_blank())
graphics.off()


Which give me the following output:
enter image description here

My questions are the following:
- how can I change the name of the legend, currently set to "variable"?
- how can I get rid of the with space on the extremity of the x axis?

Answer

To remove white space on the upper and lower bounds of the x-axis, you should add:

+ scale_x_continuous(expand = c(0, 0))

The first argument is a multiplicative factor and the second is additive, both indicating how much white space should be added to the x-axis. This will also work for the y scale.

See more at http://docs.ggplot2.org/current/scale_continuous.html.