ggplot2: coloured vertical lines - r

I'd like to create a ggplot graph with vertical lines of different colors. Here one way to achieve this goal.
mtcars$colors = rep(1:4, nrow(mtcars)/4)
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point() +
geom_vline(xintercept=subset(mtcars, colors==1)$wt, color="red") +
geom_vline(xintercept=subset(mtcars, colors==2)$wt, color="blue") +
geom_vline(xintercept=subset(mtcars, colors==3)$wt, color="yellow") +
geom_vline(xintercept=subset(mtcars, colors==4)$wt, color="green")
This solution is not very handy when the variable colors takes 50 different values 1) because it asks the user to write a very long expression (or to construct the ggplot object iteratively) and 2) because it does not produce legends for the colors. Is there a better solution?

Maybe this instead:
+ geom_vline(aes(xintercept = wt,color = factor(colors))) +
scale_color_manual(values = c('red','blue','yellow','green'))

Related

Legends in ggplot

I am trying plot this data, and the line graph is correct, but I can't make the legend show up. Any thoughts?
ggplot(data, aes(x=time_months, size=I(1))) +geom_line(aes(y=monthly_net_revenue, color=I("blue"))) +
geom_line(aes(y=cumsum(discounted_monthly_net_revenue), color=I("purple"))) +
geom_line(aes(y=monthly_expenses, color=I("red"))) +
geom_line(aes(y=cumsum(monthly_revenue), color=I("green")))
This will probably work for you
ggplot(data, aes(x=time_months, size=I(1))) +
geom_line(aes(y=monthly_net_revenue, color="blue")) +
geom_line(aes(y=cumsum(discounted_monthly_net_revenue), color="purple")) +
geom_line(aes(y=monthly_expenses, color="red")) +
geom_line(aes(y=cumsum(monthly_revenue), color="green")) +
scale_color_identity(guide = "legend")
The scale_color_identity() uses the values you pass to color= directly as the color rather than treating them like a group name. You don't need I() with this method.

ggplot2 z order of multiple geoms (background to foreground)

I am trying to plot multiple lines with surrounding area, using ggplot2, with geom_ribbon for the are, and a centerline with geom_line. The values are overlapping, but I'd like each ribbon/line combination to be either bottom or top as a combination.
Here's a reproducible example:
library(ggplot2)
x <- 1:10
y <- c(1+x/100, 2-x, .1*x^2)
data <- data.frame(x=rep(x,3), y=y, lower=y-1, upper=y+1, color=rep(c('green', 'blue', 'yellow'), each=10))
In the example I can get the plot I want by using this code:
ggplot() +
geom_ribbon(data=data[data$color=='green',],aes(x=x, ymin=lower, ymax=upper, fill=paste0('light',color))) +
geom_line(data=data[data$color=='green',],aes(x=x, y=y, col=color)) +
geom_ribbon(data=data[data$color=='blue',],aes(x=x, ymin=lower, ymax=upper, fill=paste0('light',color))) +
geom_line(data=data[data$color=='blue',],aes(x=x, y=y, col=color)) +
geom_ribbon(data=data[data$color=='yellow',],aes(x=x, ymin=lower, ymax=upper, fill=paste0('light',color))) +
geom_line(data=data[data$color=='yellow',],aes(x=x, y=y, col=color)) +
scale_color_identity() +
scale_fill_identity()
But when I keep it simple and us this this code
plot <- ggplot(data=data) +
geom_ribbon(aes(x=x, ymin=lower, ymax=upper, fill=paste0('light',color))) +
geom_line(aes(x=x, y=y, col=color)) +
scale_color_identity() +
scale_fill_identity()
the lines of the background data go over the 'top' ribbons, or if I switch the geom_line and geom_ribbon, my middle-lines are no longer visible.
For this example, the lengthy call works, but in my real data, I have a lot more lines, and I'd like to be able to switch lines from background to foreground dynamically.
Is there any way that I can tell ggplot2 that there is an ordering that has to switch between my different geoms?
P.S. I can't post images yet, sorry if my question seems unclear.
You could save some typing with a loop
ggplot(data=data) +
purrr::map(.x = split(data, f = data$color),
.f = function(d){
list(geom_ribbon(data=d,aes(x=x, ymin=lower, ymax=upper), fill=paste0('light',unique(d$color))),
geom_line(data=d,aes(x=x, y=y), col=unique(d$color)))
})

ggplot remove or replace the 'a' in geom_text legends

I trying to remove the little a in front of a legend but without any luck. Other possibility would be to create a legend or legend like text next to the graph but I am running out of ideas. Maybe someone can help me.
I plot on specific positions a red X and I want to point out, that the X marked things are imputed...
df <- data.frame(x=rnorm(10),y=rnorm(10))
ggplot(df, aes(x=x, y=y)) + geom_point() + geom_text(aes(x=0,y=0, color=factor(1)), label='X') +
scale_color_manual(values = 'red', name='imputed',labels='imputed') +
theme(legend.key=element_blank(), legend.title=element_blank())
I think the best result would be to replace the little a by a X. But I could not find any solution for it.
The problem is that you use geom_text to draw the cross.
A simple way to solve it is to use geom_point to plot the cross:
ggplot(df, aes(x=x, y=y)) + geom_point() + geom_point(aes(x=0,y=0, color=factor(1)), shape='X', size=5) +
scale_color_manual(values = 'red',labels='imputed') +
theme(legend.key=element_blank(), legend.title=element_blank())

How to combine 2 plots (ggplot) into one plot?

By using R, is it possible to place 2 ggplot together (i.e., on the same plot)? I wish to show a trend from 2 different data frames and instead of putting them one next to the other, I'd like to integrate them together in one plot and only to change the color of one of them (the black dot).
To be more specific, I have the following 2 visuals:
ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + geom_smooth(fill="blue", colour="darkblue", size=1)
and
ggplot(visual2, aes(ISSUE_DATE,COUNTED)) + geom_point() + geom_smooth(fill="red", colour="red", size=1)
They look like this (both have black dots and I'll need to change one of them to something different):
and
Creating a single combined plot with your current data set up would look something like this
p <- ggplot() +
# blue plot
geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
colour="darkblue", size=1) +
# red plot
geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
colour="red", size=1)
however if you could combine the data sets before plotting then ggplot will
automatically give you a legend, and in general the code looks a bit cleaner
visual1$group <- 1
visual2$group <- 2
visual12 <- rbind(visual1, visual2)
p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
geom_point() +
geom_smooth(size=1)
Dummy data (you should supply this for us)
visual1 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
visual2 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
combine:
visuals = rbind(visual1,visual2)
visuals$vis=c(rep("visual1",100),rep("visual2",100)) # 100 points of each flavour
Now do:
ggplot(visuals, aes(ISSUE_DATE,COUNTED,group=vis,col=vis)) +
geom_point() + geom_smooth()
and adjust colours etc to taste.
Just combine them. I think this should work but it's untested:
p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() +
geom_smooth(fill="blue", colour="darkblue", size=1)
p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) +
geom_smooth(data=visual2, fill="red", colour="red", size=1)
print(p)

ggplot2: How to specify multiple fill colors for points that are connected by lines of different colors

I am new to ggplot2. I would like to create a line plot that has points on them where the points are filled with different colors than the lines (see the plot below).
Suppose the dataset I am working with is the one below:
set.seed(100)
data<-data.frame(dv=c(rnorm(30), rnorm(30, mean=1), rnorm(30, mean=2)),
iv=rep(1:30, 3),
group=rep(letters[1:3], each=30))
I tried the following code:
p<-ggplot(data, aes(x=iv, y=dv, group=group, pch=group)) + geom_line() + geom_point()
p + scale_color_manual(values=rep("black",3))+ scale_shape(c(19,20,21)) +
scale_fill_manual(values=c("blue", "red","gray"))
p + scale_shape(c(19,20,21)) + scale_fill_manual(values=c("blue", "red","gray"))
But I do not get what I want.I hope someone can point me to the right direction. Thanks!
scale_fill_manual(), scale_shape_manual() and scale_colour_manual() can be used only if you have set fill=, shape= or colour= inside the aes().
To change colour just for the points you should add colour=group inside geom_point() call.
ggplot(data, aes(x=iv, y=dv, group=group,shape=group)) +
geom_line() + geom_point(aes(colour=group)) +
scale_shape_manual(values=c(19,20,21))+
scale_colour_manual(values=c("blue", "red","gray"))

Resources