Geom_Line - Different Colour in the Same Line

geom_line - different colour in the same line

Is this what you want?

time <- seq (1,7,1)
var1 <- c(3,5,7,2,3,2,8)
var2 <- c(2,4,18,16,12,3,2)
DF <- data.frame(time, var1, var2)

ggplot(DF, aes(time, var1, colour=(var2>10))) +
geom_line(aes(group=1))

Sample Image

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

How to make one line color in geom_line to overshadow other line colors?

You could plot it separately, after the others. Something like this:

ggplot(df, aes(year, unemp), color=cntry)+
geom_line(aes(group=cntry, color=cntry), size=1.5)+
geom_line(data = df[df$cntry == 'France',], aes(group=cntry, color=cntry), size=1.5)+
scale_color_manual(values=c('dark blue','#999999','#999999','#999999','#999999','#999999'))

How to control line colors and legend at the same time for geom_line

Try this:

ggplot(data = subset(df,!is.na(df$PARAMCD)),
aes(x = ADY, y = AVAL, color = PARAMCD)) +
geom_line() +
geom_point() +
scale_colour_manual(values = c(
DIABP = "#512d69",
SYSBP = "#007254",
PULSE = "#fd9300"
),labels = c("Systolic BP", "Diastolic BP", "Pulse"))

Sample Image

Different colours of geom_line above and below a specific value

You have at least a couple of options here. The first is quite simple, general (in that it's not limited to straight-line segments) and precise, but uses base plot rather than ggplot. The second uses ggplot, but is slightly more complicated, and colour transition will not be 100% precise (but near enough, as long as you specify an appropriate resolution... read on).

base:

If you're willing to use base plotting functions rather than ggplot, you could clip the plotting region to above the threshold (2.2), then plot the segments in your preferred colour, and subsequently clip to the region below the threshold, and plot again in red. While the first clip is strictly unnecessary, it prevents overplotting different colours, which can look a bit dud.

threshold <- 2.2
set.seed(123)
stackOne=data.frame(id=rep(c(1,2,3),each=3),
y=rnorm(9,2,1),
x=rep(c(1,2,3),3))
# create a second df to hold segment data
d <- stackOne
d$y2 <- c(d$y[-1], NA)
d$x2 <- c(d$x[-1], NA)
d <- d[-findInterval(unique(d$id), d$id), ] # remove last row for each group

plot(stackOne[, 3:2], pch=20)
# clip to region above the threshold
clip(min(stackOne$x), max(stackOne$x), threshold, max(stackOne$y))
segments(d$x, d$y, d$x2, d$y2, lwd=2)
# clip to region below the threshold
clip(min(stackOne$x), max(stackOne$x), min(stackOne$y), threshold)
segments(d$x, d$y, d$x2, d$y2, lwd=2, col='red')
points(stackOne[, 3:2], pch=20) # plot points again so they lie over lines

base package, changing line colours

ggplot:

If you want or need to use ggplot, you can consider the following...

One solution is to use geom_line(aes(group=id, color = y < 2.2)), however this will assign colours based on the y-value of the point at the beginning of each segment. I believe you want to have the colour change not just at the nodes, but wherever a line crosses your given threshold of 2.2. I'm not all that familiar with ggplot, but one way to achieve this is to make a higher-resolution version of your data by creating new points along the lines that connect your existing points, and then use the color = y < 2.2 argument to achieve the desired effect.

For example:

threshold <- 2.2 # set colour-transition threshold
yres <- 0.01 # y-resolution (accuracy of colour change location)

d <- stackOne # for code simplification
# new cols for point coordinates of line end
d$y2 <- c(d$y[-1], NA)
d$x2 <- c(d$x[-1], NA)
d <- d[-findInterval(unique(d$id), d$id), ] # remove last row for each group
# new high-resolution y coordinates between each pair within each group
y.new <- apply(d, 1, function(x) {
seq(x['y'], x['y2'], yres*sign(x['y2'] - x['y']))
})
d$len <- sapply(y.new, length) # length of each series of points
# new high-resolution x coordinates corresponding with new y-coords
x.new <- apply(d, 1, function(x) {
seq(x['x'], x['x2'], length.out=x['len'])
})
id <- rep(seq_along(y.new), d$len) # new group id vector
y.new <- unlist(y.new)
x.new <- unlist(x.new)
d.new <- data.frame(id=id, x=x.new, y=y.new)

p <- ggplot(d.new, aes(x=x,y=y)) +
geom_line(aes(group=d.new$id, color=d.new$y < threshold))+
geom_point(data=stackOne)+
scale_color_discrete(sprintf('Below %s', threshold))
p

conditional line colour - ggplot

There may well be a way to do this through ggplot functions, but in the meantime I hope this helps. I couldn't work out how to draw a ggplotGrob into a clipped viewport (rather it seems to just scale the plot). If you want colour to be conditional on some x-value threshold instead, this would obviously need some tweaking.

How to plot a single line in different color and shape in R?

You could subset DF

ggplot(DF[DF$Date < as.Date("2001-06-01"), ], aes(x = Date, y = V1)) +
geom_line() +
geom_line(data = DF[DF$Date >= as.Date("2001-06-01"), ], col = "red", linetype = "dashed")

Sample Image

R - ggplot line color (using geom_line) doesn't change

Your first code should be

ggplot(data=main_data) +
# black plot
geom_line(aes(x=vectors_growth_rate_with_predator,
y=disease_prevalnce_with_predator),
color = "black") +
# blue plot
geom_line(aes(x=vectors_growth_rate_with_predator,
y=disease_prevalnce_without_predator),
color = "blue")

You need to put color outside aes().

For your second code you need to reshape your data from wide to long format. You can do this in many ways, the following should work for you.

library(tidyverse)
main_data <- main_data %>%
gather(key, value, c("disease_prevalnce_with_predator",
"disease_prevalnce_without_predator")
PrevVSGrowth <- ggplot(data=main_data) +
geom_line(aes(x=vectors_growth_rate_with_predator,
y=value,
col = key))

PrevVSGrowth +
scale_color_manual(values = c(disease_prevalnce_with_predator= 'black',
disease_prevalnce_without_predator = 'blue'))

In the first plot we set an aesthetic to a fixed value, in each call to geom_line(). This creates two new variables containing only the value "black" and "blue", respectively. In OP's example the values "black" and "blue" are then scaled to red and lightblue and a legend is added.

In the second plot we map the colour aesthetic to a variable (key in this example). This is usually the preferred way.

ggplot2: coloring segments of single line with different colors

Does this graph solve you problem?

ggplot() + geom_line(aes(x, y, group = line, color = color), data = temp)

How do I change the color of geom_line when I have multiple lines?

ggplot uses gradient color scales for continuous data and qualitiative color scales for categorical data.

Your dati$yr column must be numeric (continuous), and your dd.tot$yr column is factor (categorical). Convert with dati$yr = factor(dati$yr), or change the mapping to color = factor(yr) inside your aes().

R ggplot, set colour for one geom_line but not another

Plot mdt lines with separate geom_line layers and specify colors in them.

For name A plot mean line using: geom_line(data = mdt[name == "A"], col = "#ff5a32") with redish color. For thinner lines specify similar color with scale_color_manual.

library(data.table)
library(ggplot2)

mdt <- dt[, .(value = mean(value)), by = .(name, date)]

ggplot(dt, aes(date, value)) +
geom_line(aes(group = type, col = name)) +
geom_line(data = mdt[name == "A"], col = "#ff5a32", size = 2) +
geom_line(data = mdt[name == "B"], col = "#475cd3", size = 2) +
scale_colour_manual(name = "Name",
values = c("#ff987f", "#8c99e4")) +
labs(x = "Date",
y = "Value",
title = "Change in value over time") +
theme_classic()

Sample Image



Related Topics



Leave a reply



Submit