ggplot line plot different colors for sections
geom_path
is more suited for where you are trying to connect points: http://ggplot2.tidyverse.org/reference/geom_path.html. As explained there:
"geom_path connects the observations in the order in which they appear in the data."
I have found it to be a bit funny with factors, as you have here. As an example of what you might expect the function to look like:
ggplot(Dataset_v2.2.clusterplot, aes(Date, Number_IPOs, color = factor(label)))+
geom_path() +
geom_point()
An easy way to fix this is to specify a group for the line within the aes
for geom_path
. As you want a continuous line, I just specified 1
(this value is arbitrary, and could be any number)
ggplot(Dataset_v2.2.clusterplot, aes(Date, Number_IPOs, color = factor(label)))+
geom_path(aes(group = 1)) +
geom_point()
Using a different color for a section of a line in ggplot
Here is a solution where you just need to subset your data to draw each line.
library(ggplot2)
#Number of rows, from 1 to n, where the lines overlap.
#According to your question this should be 138 using the complete dataset
n<-5
ggplot(data = xcel, aes(x = Year)) +
#Subset data for black line, i.e., shared line
geom_line(aes(y = GLocation45), data = xcel[1:n,],
color = "black", linetype = "twodash") +
#Subset for the red line. i.e., rest of the data
geom_line(aes(y = GLocation85), data = xcel[n:nrow(xcel),],
color = "red", linetype = "twodash") +
#Draw green line normally, without subsets
geom_line(aes(y = Glocationco),
color = "green", linetype = "twodash")
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))
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")
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 to make a (ggplot) line plot with different color segments conditional on direction
Your merge didn't work because you only had two colour variables, but three data values. Adding a third colour variable as padding seems to do the trick. geom_line takes it's colour from the previous datapoint's value, so the last value of "value2" is not used.
d$farve3<-NA
dm1 <- melt(d[,c("Type","I.alt","idx06","idx07","idx08")], id=c("Type","I.alt"))
dm2 <- melt(d[,c("Type","I.alt","farve1","farve2","farve3")], id=c("Type","I.alt"))
colnames(dm2) <- c("Type", "I.alt", "variable2", "value2")
dm<-cbind(dm1,dm2)
ggplot(dm, aes(x=variable,y=value,group=Type,label=Type,size=I.alt))+
geom_line(aes(col=value2))+
geom_text(data=subset(dm, variable=="idx08"),hjust=-0.2, size=2.5)+
theme_bw()+
scale_x_discrete(expand=c(0,1))+
opts(legend.position="none")+
scale_colour_manual(values=c("green","red"))
Two lines in ggplot: change colors for segments
library(ggplot2)
ggplot(df) +
geom_line(aes(x = Date, y = Close), color = "red", size = 1) +
geom_line(aes(x = Date, y = Popularity), color = "blue", size = 1) +
geom_line(data = df[df$Date >= as.Date("2017-10-22") & df$Date <= "2018-01-28",],
aes(x = Date, y = Close), color = "black", size =1) +
geom_line(data = df[df$Date >= as.Date("2017-10-22") & df$Date <= "2018-01-28",],
aes(x = Date, y = Popularity), color = "green", size = 1) +
theme_classic()
Plotting a line in ggplot with three different subsets with different colors
If you want separate purple lines for each series distinguished by the Recorte
column, you can use geom_line(aes(group = Recorte), color = "purple")
If you want separate lines with different colors, you could use geom_line(aes(color = Recorte))
and combine that with something like scale_color_manual(values = c("Periodo 1" = "purple", "Periodo 2" = "darkorchid", "Periodo 3" = "darkmagenta"))
if you want to specify different purple colors for the various series.
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
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
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.
Related Topics
Mass Variable Declaration and Assignment in R
Levenshtein Type Algorithm with Numeric Vectors
Increasing Whitespace Between Legend Items in Ggplot2
R - Pivoting Duplicate Rows into Multiple Column with Unknown Number of Columns
How to Select Dropdown Box Using Rselenium
Choose Specific Number with Probability
Cumulative Minimum Value by Group
Fread and a Quoted Multi-Line Column Value
How to Do a Glm When "Contrasts Can Be Applied Only to Factors with 2 or More Levels"
Predict.Lm in R Fails to Recognize Newdata
Getting the Minimum of the Rows in a Data Frame
Create a New Column with Non-Null Columns' Names
R: Split String into Numeric and Return the Mean as a New Column in a Data Frame
Chi Square Test for Each Row in Data Frame
R - Converting Posixct to Milliseconds
Select a Sequence of Columns: ':' Works But Not 'Seq'
How to Extract Text from R's Help Command
Variable Results with Dplyr Summarise, Depending on Output Variable Naming