I am trying to plot a line plot in r by using ggplot. Unfortunately, the legend does not show up. Can anyone help me?
My code looks like the following:
dfdatavgsM=data.frame(datum, avgsätzegespMT, avgsätzegespML)
ggplot(data = dfdatavgsM, aes(x=datum, color=Wettbewerbsart))
+ geom_line(data=dfdatavgsM, aes(y = avgsätzegespML),color="red")
+ geom_line(data=dfdatavgsM, aes(y = avgsätzegespMT), color="blue")
+ geom_vline(xintercept=2011, size = 0.6)
+ scale_y_continuous(name="Anzahl an Sätzen")
+ scale_x_datetime(name = "Saison" ,date_breaks = ("2 year"),date_labels = "%Y")
+ ggtitle("Wettbewerbsintensität in Spielen mit |∆TTR| ≤ 118") + theme(panel.background = element_rect(fill = "white", colour = "black"))
+ theme(panel.grid.major = element_line(size = 0.25, linetype = 'solid', colour = "light grey")) + theme(axis.ticks = element_line(size = 1))
The legend will only appear if you use color inside an aes statement. You will need to reshape your data to 'long' format (e.g. with tidyr::gather), and have a single geom_line term and an aes including color=type. Something like this (not tested as I don't have your data)...
library(tidyverse)
dfdatavgsM=data.frame(datum, avgsätzegespMT, avgsätzegespML)
dfdatavgsMlong <- dfdatavgsM %>% gather(key = type, value = value, -datum)
ggplot(data = dfdatavgsMlong, aes(x=datum, y=value, color=type)) +
geom_line()
Related
i need the plan legend
How to add a legend manually for geom_line
ggplot(data = impact_end_Current_yr_m_actual, aes(x = month, y = gender_value)) +
geom_col(aes(fill = gender))+theme_classic()+
geom_line(data = impact_end_Current_yr_m_plan, aes(x=month, y= gender_value, group=1),color="#288D55",size=1.2)+
geom_point(data = impact_end_Current_yr_m_plan, aes(x=month, y=gender_value))+
theme(axis.line.y = element_blank(),axis.ticks = element_blank(),legend.position = "bottom", axis.text.x = element_text(face = "bold", color = "black", size = 10, angle = 0, hjust = 1))+
labs(x="", y="End Beneficiaries (in Num)", fill="")+
scale_fill_manual(values=c("#284a8d", "#00B5CE","#0590eb","#2746c2"))+
scale_y_continuous(labels = function(x) format(x, scientific = FALSE)
The neatest way to do it I think is to add colour = "[label]" into the aes() section of geom_line() then put the manual assigning of a colour into scale_colour_manual() here's an example from mtcars (apologies that it uses stat_summary instead of geom_line but does the same trick):
library(tidyverse)
mtcars %>%
ggplot(aes(gear, mpg, fill = factor(cyl))) +
stat_summary(geom = "bar", fun = mean, position = "dodge") +
stat_summary(geom = "line",
fun = mean,
size = 3,
aes(colour = "Overall mean", group = 1)) +
scale_fill_discrete("") +
scale_colour_manual("", values = "black")
Created on 2020-12-08 by the reprex package (v0.3.0)
The limitation here is that the colour and fill legends are necessarily separate. Removing labels (blank titles in both scale_ calls) doesn't them split them up by legend title.
In your code you would probably want then:
...
ggplot(data = impact_end_Current_yr_m_actual, aes(x = month, y = gender_value)) +
geom_col(aes(fill = gender))+
geom_line(data = impact_end_Current_yr_m_plan,
aes(x=month, y= gender_value, group=1, color="Plan"),
size=1.2)+
scale_color_manual(values = "#288D55") +
...
(but I cant test on your data so not sure if it works)
I am trying to make a boxplot with this basic code:
design=c("Red","Green","Blue")
actions=c("1","2","3","4","5","6","7","8")
proportion=(seq(1:240)+sample(1:500, 240, replace=T))/2000
df=data.frame(design, actions , proportion)
ggplot(df, aes(x=actions, y=proportion, fill=design)) +
geom_boxplot()+
xlab(TeX("group"))+
ylab("Y value")+
ggtitle("Y values for each group stratified by color")
Producing something like this:
I want to add horizontal lines for "true" Y values that are different for each group.
Does anyone have any tips for doing this? I don't know how to extract the width of each group of boxes, otherwise I could use geom_segment.
Here is a MWE with a non-grouped boxplot:
dBox <- data.frame(y = rnorm(10),group="1")
dBox=rbind(dBox,data.frame(y=rnorm(10),group="2"))
dLines <- data.frame(X =c(-0.36, 0.015),
Y = c(0.4, -0.2),
Xend = c(0.-0.015, 0.36),
Yend=c(0.4, -0.2),
group = c("True", "True"),
color = c("black", "red"))
ggplot(dBox, aes(x=0, y=y,fill=group)) +
geom_boxplot(outlier.shape = 1)+
geom_segment(data = dLines, aes(x = X, xend = Xend, y = Y, yend = Yend),color="red",size=1.5,linetype=1) +
theme(legend.background = element_rect(fill = "white", size = 0.1, linetype = "solid", colour = "black"))
This produces something like this:
However, it's difficult to make the geom_segments line up with the boxes exactly, and to then extend this to the grouped boxplot setting.
Thanks!
This can be done using a workaround with facets:
lines = data.frame(actions = 1:8, proportion=abs(rnorm(8)))
design=c("Red","Green","Blue")
actions=c("1","2","3","4","5","6","7","8")
proportion=(seq(1:240)+sample(1:500, 240, replace=T))/2000
df=data.frame(design, actions , proportion)
lines = data.frame(actions = 1:8, proportion=abs(rnorm(8)))
p = ggplot(df, aes(x=actions, y=proportion, fill=design)) +
geom_boxplot()+
xlab("group")+
ylab("Y value")+
ggtitle("Y values for each group stratified by color") +
facet_grid(~actions, scale='free_x') +
theme(
panel.spacing.x = unit(0, "lines"),
strip.background = element_blank(),
strip.text.x = element_blank())
p + geom_hline(aes(yintercept = proportion), lines)
You could probably fiddle around with removing the spaces between the facets to make it look more like what you intended.
Thanks to #eugene100hickey for pointing out how to remove spacing between facets.
theme(panel.spacing.x) can remove those pesky lines:
p + geom_hline(aes(yintercept = proportion), lines) +
theme(panel.spacing.x = unit(0, "lines"))
I´m trying to get just one legend with shape that have the same color as the graph but it is just in black color:
type1 <-c("tmax","tmax","tmax","tmin","tmin","tmin","tmax","tmax","tmax","tmin","tmin","tmin")
station1 <-c("Anda","Anda","Anda","Anda","Anda","Anda","Mach","Mach","Mach","Mach","Mach","Mach")
date1 <-c(2001,2002,2003,2001,2002,2003,2002,2003,2004,2002,2003,2004)
meanTemp1<-c(15,16,15.5,5,7,8,13,14,12,9,9,7)
data11 <- data.frame(type1,station1,date1,meanTemp1)
plot1<- ggplot(data11, aes(x=date1, y=meanTemp1,group = station1,colour=station1,shape=station1)) +
geom_line () + guides(colour=FALSE)+
geom_point() +
xlab("year") + ylab("°C") +
labs(shape = "Station")+
facet_wrap(~type1,scales = "free")+
theme(axis.text.x = element_text(angle = 60,hjust = 1))
plot1
How can I get the legend fill with the same color as the graph instead of "black"?
As you rename shape legend in labs, you also need to rename colour legends using the same name in order they get merge.
Instead of using guides(colour = FALSE), you can pass in geom_line, the argument show.legend = FALSE to remove the colored lines in the legend:
plot1<- ggplot(data11, aes(x=date1, y=meanTemp1, group = station1,
colour=station1,
shape=station1)) +
geom_line (show.legend = FALSE) +
geom_point() +
xlab("year") + ylab("°C") +
labs(shape = "Station", colour = "Station")+
facet_wrap(~type1,scales = "free")+
theme(axis.text.x = element_text(angle = 60,hjust = 1))
plot1
Following guides like ggplot Donut chart I am trying to draw small gauges, doughnuts with a label in the middle, with the intention to put them later on on a map.
If the value reaches a certain threshold I would like the fill of the doughnut to change to red. Is it possible to achieve with if_else (it would be most natural but it does not work).
library(tidyverse)
df <- tibble(ID=c("A","B"),value=c(0.7,0.5)) %>% gather(key = cat,value = val,-ID)
ggplot(df, aes(x = val, fill = cat)) + scale_fill_manual(aes,values = c("red", "yellow"))+
geom_bar(position="fill") + coord_polar(start = 0, theta="y")
ymax <- max(df$val)
ymin <- min(df$val)
p2 = ggplot(df, aes(fill=cat, y=0, ymax=1, ymin=val, xmax=4, xmin=3)) +
geom_rect(colour="black",stat = "identity") +
scale_fill_manual(values = if_else (val > 0.5, "red", "black")) +
geom_text( aes(x=0, y=0, label= scales::percent (1-val)), position = position_dodge(0.9))+
coord_polar(theta="y") +
xlim(c(0, 4)) +
theme_void() +
theme(legend.position="none") +
scale_y_reverse() + facet_wrap(facets = "ID")
Scale fill manual values= if else.... this part does not work, the error says: Error in if_else(val > 0.5, "red", "black") : object 'val' not found. Is it my error, or some other solution exists?
I also realize my code is not optimal, initially gather waited for more variables to be included in the plot, but I failed to stack one variable on top of the other. Now one variable should be enough to indicate the percentage of completion. I realise my code is redundant for the purpose. Can you help me out?
A solution for the color problem is to first create a variable in the data and then use that to map the color in the plot:
df <- tibble(ID=c("A","B"),value=c(0.7,0.5)) %>% gather(key = cat,value = val,-ID) %>%
mutate(color = if_else(val > 0.5, "red", "black"))
p2 = ggplot(df, aes(fill=color, y=0, ymax=1, ymin=val, xmax=4, xmin=3)) +
geom_rect(colour="black",stat = "identity") +
scale_fill_manual(values = c(`red` = "red", `black` = "black")) +
geom_text( aes(x=0, y=0, label= scales::percent (1-val)), position = position_dodge(0.9))+
coord_polar(theta="y") +
xlim(c(0, 4)) +
theme_void() +
theme(legend.position="none") +
scale_y_reverse() + facet_wrap(facets = "ID")
The result would be:
I have the following ggplot and trying to add the legend and a geom_abline at median.
purple line is for 2013 prods and red is for 2014
This is what I did to generate the plot:
ggplot(prods[Year==2013,], aes(x = Date, y = Prod, group = SOM)) +
geom_line(lwd = 1.3, colour = "purple") +
ylab("Actual Productivity") + theme(axis.title.x=element_blank()) +
geom_line(data=prods[Year==2014,], aes(x = Date, y = Prod, group = SOM),lwd = 1.3, colour = "red") +
geom_abline(data = prods,h=median(Prod))+
scale_color_manual("Period", values = c("purple","red"), labels = c("2013","2014")) +
facet_wrap(~ SOM)
I am not getting any error but there is no legend nor abline is popping up on the image. Plot looks like
this:
any help would be highly appreciated.
regards,
As per aosmith's advice:
I did the following and was able to get the following plot:
ggplot(data=prods,aes(Date)) +
geom_line(data=prods[Year==2013,],aes(y=Prod, colour="red"),lwd = 1.3,) +
geom_line(data=prods[Year==2014,],aes(y=Prod, colour="blue"),lwd = 1.3) +
geom_hline(data=prods, aes(yintercept = median(Prod))) +
scale_colour_manual(name="Period",values=c("blue","red", "black"), labels = c("2014","2013", "Median")) +
ylab("Actual Prod") + xlab(" ") +
theme(axis.title.y = element_text(size = 15, vjust=0.3)) +
facet_wrap(~ SOM)
Plot looks like this: