Legend in ggplot2, remove level - r

My data:
df <- data.frame(sp = c(LETTERS[1:8]),
tr = c("NS", "LS", "NS", "LS", "LS", "HS", "HS", "HS"),
bv = c(14, 5, 11, 5.6, 21, 5.4, 2, 4.8),
av = c(0.0, 14, 21, 48.4, 15, 55.6, 37, 66.2))
I do the bar plot
library(reshape2)
df1 <- melt(df, id.vars = c("sp", "tr"))
ggplot(aes(sp, value, fill = variable) , data = df1) + theme_classic() +
geom_bar(aes(lty = tr), lwd = 1.2, data = df1, stat = "identity", colour = "black", width =.8) +
theme(legend.position = "bottom" ) +
scale_linetype_discrete(name = "ja")
Output
What I does not like is the legend. I'd like to have just the lines type from the second part "ja" and remove "variable" part. I'd like to have the white background in the legend boxes, not the grey one.

You can remove the variable legend by setting fill = FALSE in guides and you change the backgroundcolor with override.aes in guide_legend (also inside guides) as follows:
ggplot(df1, aes(sp, value, fill = variable)) +
geom_bar(aes(lty = tr), lwd = 1.2, stat = "identity", colour = "black", width =.8) +
scale_linetype_discrete(name = "ja") +
guides(fill = FALSE,
lty = guide_legend(override.aes = list(lty = c('dotted', 'dashed', 'solid'),
fill = "white"))) +
theme_classic() +
theme(legend.position = "bottom")
this results in the following plot:

Related

How to fill stat_ellipse with patterns with transparent backgrounds in R?

I am using stat_ellipse in R to generate ellipse area polygons from the data. However, they overlap significantly and turning the alpha level to transparent "kind of" works. I wanted to see if there was a way to fill specific ellipses with a pattern that has a transparent background since they overlap so much. Maybe I could have some solid colors and others patterns?
This is my working plot code now:
ggplot(data = claw3,
aes(x = iso1,
y = iso2,
fill = group,
lty = community,
shape = community)) +
stat_ellipse(aes(group = interaction(group, community),
lty = community),
alpha = 0.85, #trasparent level trying to make 2012 West more visible
color = "black",
level = p.ell,
type = "norm",
geom = "polygon",
size = 1.1) +
geom_point(aes(fill = group), size = 2, alpha = 1, color = "black") +
scale_fill_manual(values = c("blue", "grey30","00FFFFFF"),labels = c("2012", "2014","2016"))+
scale_color_manual(values = c( "blue", "grey30","00FFFFFF"))+
scale_linetype_manual(values = c("dotted","solid"))+
scale_shape_manual(values = c(21, 24))+
guides(shape = guide_legend(override.aes = list(fill = "white")), #overrides legend for the community boxes filled white
fill = guide_legend(override.aes = list(shape = NA, size = 1))) + #overrides legend for group removes shapes in year
ylab(expression(paste(delta^{15}, "N (\u2030)"))) +
xlab(expression(paste(delta^{13}, "C (\u2030)"))) +
scale_x_continuous(breaks= seq(-26.5, -19.5, by = 1),
#labels = c( -24, rep("", 2), -23, rep("", 2), -21),
limits = c(-26.5, -19.5),
expand = c(0, 0)) +
scale_y_continuous(breaks= seq(4, 11),
labels = c(4, "",6, "",8, "", 10, ""),
limits = c(3.5, 11),
expand = c(0, 0)) +
theme(text = element_text(size=14)) +
theme_classic(base_size = 14) +
theme(legend.title = element_blank())
I have recently found ggpattern, but it does not look like its friendly with stat_ellipse or I really just don't understand where to put it. I believe Id have to remove the scale_fill_manual and scale_color_manual commands, but thats about it.

Align asterisk of geom point ggplot with position dodge

I am trying to align significance asterisks (* or ** or ***) to the points of a geom point graph with position dodge to indicate the significance of a value using ggplot2. I wasn't able to find any similar questions and answers with similar issue.
Here is data frame 'df':
df<-data.frame(conc=c(1,10,100,1, 10,100,1, 10, 100),
mean=c( 0.9008428,0.8278645,0.7890388,0.9541905,
0.8537885,0.8212504,1.3828724,0.7165685, 0.7985398),
Treatment=c("A","A","A","B", "B", "B","C","C", "C"),
upper =c(1.0990144, 0.9505348, 0.8273494, 1.0389074, 0.9227461, 0.9657371, 1.6864420, 0.7401891, 0.9046951),
lower=c(0.7026713, 0.7051941, 0.7507282, 0.9528077, 0.7848309, 0.6767638, 1.0793029, 0.6929479, 0.6923846),
p.value=c(0.0003, 0.6500, 1,0.02,0.0400,
0.3301,0.100,0.023, 0.05))
I made a plot with an automatic asterisk, but it is not aligned how i want to, and i believe it's because of position_dodge, but i have too many points in one concentration, so i have to use it (given data frame is minimal).
legend_title <- "Treatment"
breaks_y =c(0, 0.25, 0.5, 0.75, 1, 1.25, 1.5)
breaks = c(1, 10, 100)
df$Label <- NA
df$Label[df$p.value<0.001]<-'***'
df$Label[df$p.value<0.01 & is.na(df$Label)]<-'**'
df$Label[df$p.value<0.05 & is.na(df$Label)]<-'*'
ggplot(df, aes(x = conc, y = mean, color = Treatment)) +
geom_errorbar(aes(ymax = upper, ymin = lower, width = 0),position = position_dodge(width=0.5)) +
geom_point(aes(shape = Treatment, fill = Treatment), size = 4, position = position_dodge(width=0.5)) +
geom_text(aes(label = Label),size = 4, position = position_dodge(width =0.5), color = "black") +
scale_shape_manual(values = c(22, 21, 23)) +
scale_color_manual(values=c('blue','coral1', 'darkgreen' )) +
scale_fill_manual(values=c('blue','coral1', 'darkgreen')) +
labs(x = "Concentration (\u03BCM)", y = "Abs", title = "Viability", fill = "Treatment") +
scale_x_continuous(trans="log10", limits = c(0.5, 170), breaks = breaks) +
scale_y_continuous(limits = c(0, 1.5), breaks = breaks_y) +
theme_light() +
ggpubr::rotate_x_text(angle = 70) +
theme(axis.text = element_text(size = 12, face = "bold"),
axis.title.y = element_text(size = 12, face ="bold"),
axis.title.x = element_text(size = 12, face ="bold"))
How can I align the asterisk automatically to be directly above the correct dot with position_dodge?

Legend mixing shapes with geom_points R

My legend is not showing correctly when I am doing my graph in R using ggplot2. One column of my dataset is represented by a geom_bar and the two others are represented by geom_points (one shape each). The circle and the diamond shape are showing for both 2000 and 2008, the circle being in the diamong for both year. However, the graph works totally fine...
Here is a screenshot:
I have created a simplified version of my dataset:
order_var <- c(1, 4, 3, 5, 6, 2)
alt_name <- c('Agriculture', 'Mining', 'Food products',' Manufacture', 'Chemicals', 'Machinery')
y2000 <- c(20, 40, 50, 80, 30, 70)
y2008 <- c(40, 50, 80, 70, 30, 60)
y2018 <- c(10, 30, 80, 50, 40, 50)
datatest <- data.frame("order_var" = order_var, "alt_name" = alt_name, "y2000" = y2000, "y2008" = y2008, "y2018" = y2018)
And the code for my graph:
datatest %>% ggplot(aes(x = reorder(alt_name, order_var))) +
geom_bar(stat = "identity", aes(y = `y2018`, fill = "2018"), width = 0.7, col = "black") +
geom_point(aes(y = `y2008`, col = "2008"), shape = 23, fill = "white", size = 5) +
geom_point(aes(y = `y2000`, col = "2000"), shape = 19, fill = "black", size = 3) +
xlab("Industry") +
ylab("Percentage") +
theme(legend.position = "top") +
scale_fill_manual(name = '', values = c("2018" = "#4F81BD"), breaks = c("2018")) +
scale_colour_manual(name = '', values = c("2008" = "black", "2000" = "orange"))
If you know how to correct this problem, I would be very grateful!!
Thank you :)
That's a very tricky plot you are trying to make because you are in essence mapping the same aesthetics to different geoms.
The first thing you should do is to reshape your data to the long format. I also divided your dataset between 2018 (the bar), and 2000, 2008 (the points).
df2 <- datatest %>%
pivot_longer(cols = -c(order_var, alt_name)) %>%
mutate(bar = if_else(name == "y2018", 1, 0))
data_bar <- df2 %>% filter(bar == 1)
data_point <- df2 %>% filter(bar != 1)
I also find it useful to add a dodge to your points to avoid overlapping one inside the other as in the case of chemicals with position = position_dodge(width = 0.6).
The first solution gives what you want, but it is a bit of a hack, and I wouldn't recommend doing it as a general strategy. You basically add an aesthetics that you are not going to use to the bars (in this case, linetype), and then override it, as suggested in this answer.
ggplot(data_bar, aes(x = reorder(alt_name, order_var))) +
geom_bar(aes(y = value, linetype = name), fill = "#4F81BD", stat = 'identity', color = 'black') +
geom_point(data = data_point, position=position_dodge(width=0.6), aes(y = value, color = name, shape = name, size = name, fill = name)) +
scale_colour_manual(values = c("orange", "black"), labels = c("2000", "2008")) +
scale_fill_manual(values = c("orange", "white"), labels = c("2000", "2008")) +
scale_shape_manual(values = c(19, 23), labels = c("2000", "2008")) +
scale_size_manual(values = c(3, 5), labels = c("2000", "2008")) +
scale_linetype_manual(values = 1, guide = guide_legend(override.aes = list(fill = c("#4F81BD"))), labels = c("2018")) +
theme(legend.position = "top", legend.title = element_blank()) +
labs(x = "Industry", y = "Percentage")
Another solution, more general, is to avoid using the fill aesthetics for the geom_point and changing the shape to a solid one instead:
ggplot(data_bar, aes(x = reorder(alt_name, order_var))) +
geom_bar(aes(y = value, fill = name), stat = 'identity', color = "black") +
geom_point(data = data_point, position=position_dodge(width=0.6), aes(y = value, color = name, shape = name, size = name)) +
scale_fill_manual(values = c("#4F81BD"), labels = c("2018")) +
scale_colour_manual(values = c("orange", "white"), labels = c("2000", "2008")) +
scale_shape_manual(values = c(19, 18), labels = c("2000", "2008")) +
scale_size_manual(values = c(4, 6), labels = c("2000", "2008")) +
theme(legend.position = "top", legend.title = element_blank()) +
labs(x = "Industry", y = "Percentage")

How to add the legend to combo plot?

Here is the data set:
d <- tribble(
~priceseg, ~price_n, ~zet_n, ~zet_n2,
"(0,1]", 16, 2, 24,
"(1,3]", 33, 3, 38,
"(3,5]", 33, 2, 25,
"(5,6]", 17, 1, 13,
)
And here is the visualisation thanks to #d.b
ggplot(d) +
geom_col(aes(x = priceseg, y = price_n), fill = ("#F1948A"), colour="black", size = 0.6) +
geom_line(data = d, mapping = aes(x = priceseg, y = zet_n2, group = 1), colour = "#154360", size = 1) +
geom_label(data = d, mapping = aes(x = priceseg, y = price_n, label = price_n), nudge_y = -0.6)
Now, I want to add the legend for bar plot and line in the visualisation something like this: Combined line & bar geoms: How to generate proper legend?
Also, I would like to add % in geom_label.
But somehow, I could not manage to implement it. Any help?
Here is an option
# Calculate percentage and add as column to `d`
d <- transform(d, perc = sprintf("%2.1f%%", price_n / sum(price_n) * 100))
# Plot
ggplot(d, aes(x = priceseg)) +
geom_col(aes(y = price_n, fill = "bar_data"), colour = "black", size = 0.6) +
geom_line(aes(y = zet_n2, group = 1, colour = "line_data"), size = 1) +
scale_fill_manual("", values = "#F1948A") +
scale_colour_manual("", values = "#154360") +
geom_label(aes(y = price_n, label = perc), nudge_y = -0.6) +
theme(
legend.key = element_blank(),
legend.title = element_blank(),
legend.box = "horizontal")
You can adjust the fill and colour "labels" by changing the strings "bar_data" and "line_data".

How to type subscripts in geom_text labels in ggplot

I have timeseries data plotted and separated by timepoints that I'd like to label with subscripts. Below is the code I'm using to generate the figure and timepoint labels. I'd like for the -1, 3 and 6 to be subscripts. Thanks in advance!
timepoints=data.frame(date=as_datetime(c("2016-08-15" ,"2016-11-22",
"2017-02-25")), timepoint=c("T-1", "T3", "T6"))
TimeseriespH = ggplot(FinalSeaphox, aes(x=DTTM)) +
geom_line(aes(y=MpH, color = "Outer Bay", group = grp), size = 0.5) +
geom_line(aes(y=CpH, color = "Inner Bay", group = grp), size = 0.5) +
scale_x_datetime(labels = date_format("%b '%y"), date_breaks = "1
month", limits = as_datetime(c("2016-07-01","2017-04-19"))) +
labs(x = "", y = "pH") +
scale_y_continuous(limits = c(7.4,8.2)) +
geom_vline(xintercept = as_datetime("2016-12-01"), linetype = 2, color
= "black") +
geom_vline(xintercept = as_datetime("2016-08-26"), linetype = 2, color
= "black") +
geom_vline(xintercept = as_datetime("2017-03-06"), linetype = 2, color
= "black") +
geom_text(data=timepoints, mapping=aes(x=date, y=c(8.18, 8.18, 8.18),
label=timepoint), size=5, vjust=-0.4, hjust=0, inherit.aes = FALSE,
color = "black")
For the subscripts, you need to enclose between brackets:
timepoint = c("T[-1]", "T[3]", "T[6]")
Then use parse = TRUE in geom_text:
library(ggplot2)
library(lubridate)
timepoints=data.frame(
date = as_datetime(c("2016-08-15" ,"2016-11-22", "2017-02-25")),
Y = c(8, 8.1, 8)
timepoint = c("T[-1]", "T[3]", "T[6]")
)
ggplot(timepoints) +
geom_point(aes(x = date, y=Y), size = 3) +
geom_text(data=timepoints,
mapping=aes(x=date, y=c(8.18, 8.18, 8.18),
label = timepoint),
size=5, vjust=0.4, hjust=0, inherit.aes = FALSE,
color = "black", parse = TRUE)

Resources