I have a dataframe of some spectra (one x-value, several y-values) and want to plot them in one graph. For this purpose, I want to use ggplot. After some research, I found a way to do so, but I want to change the color of the lines from black to grey, representing a dcrease in concentration.
if (!require("ggplot2")) install.packages("ggplot2")
set.seed(230527)
df.tmp <- data.frame(x = runif(25),
y = cbind(runif(25),
runif(25),
runif(25),
runif(25),
runif(25))
)
if (!require("reshape")) install.packages("reshape")
df.spec <- data.frame(x = df.tmp[,1], y = df.tmp[,2:6])
df.spec <- melt(df.spec, id.vars = "x")
ggplot(df.spec, aes(x = x, y = value, color = variable)) +
geom_line()
Therefore, I defined a color palette.
palette.spec <- fields::designer.colors(col = c("black", "lightgrey"), n = NCOL(df.tmp)-1)
if (!require("ggplot2")) install.packages("ggplot2")
set.seed(230527)
df.tmp <- data.frame(x = runif(25),
y = cbind(runif(25),
runif(25),
runif(25),
runif(25),
runif(25))
)
palette.spec <- fields::designer.colors(col = c("black", "lightgrey"), n = NCOL(df.tmp)-1)
if (!require("reshape")) install.packages("reshape")
df.spec <- data.frame(x = df.tmp[,1], y = df.tmp[,2:6])
df.spec <- melt(df.spec, id.vars = "x")
ggplot(df.spec, aes(x = x, y = value, color = variable)) +
geom_line() +
scale_color_manual(values = palette.spec)
Now, the color of the lines and the legend fits, but I also have to change the names of the legend entries.
When doing so, the names are correct, but also the color of the lines in the graph changes.
if (!require("ggplot2")) install.packages("ggplot2")
set.seed(230527)
df.tmp <- data.frame(x = runif(25),
y = cbind(runif(25),
runif(25),
runif(25),
runif(25),
runif(25))
)
palette.spec <- fields::designer.colors(col = c("black", "lightgrey"), n = NCOL(df.tmp)-1)
if (!require("reshape")) install.packages("reshape")
df.spec <- data.frame(x = df.tmp[,1], y = df.tmp[,2:6])
df.spec <- melt(df.spec, id.vars = "x")
ggplot(df.spec, aes(x = x, y = value, color = variable)) +
geom_line() +
scale_color_manual(values = palette.spec,
limits = c("A", "B", "C", "D", "E"))
Is it possible to match the colors of the lines and the legend entries?
Bonus: Is it also possible to insert a manual offset between the different lines?
By setting limits
you are defining the valid values for the colour scale.
Because none of the values in variable
match them, they get mapped to NA
and a corresponding grey colour.
Instead of specifying limits
, either define the variable labes in your
data, or use labels
:
ggplot(df.spec, aes(x = x, y = value, color = variable)) +
geom_line() +
scale_color_manual(
values = palette.spec,
labels = c("A", "B", "C", "D", "E")
)