I have the following two-axis line chart created in ggplot2
:
#data
datos_graficos <- data.frame(
Arena = c(20,25,30,35,40,45,50),
Media_Mg = c(0.3050000,0.3025000,0.2775000,0.3157143,0.2887500,0.2928571,0.3225000),
SE_Mg = c(0.02160155,0.02160155,0.02160155,0.02309303,0.02160155,0.02309303,0.02160155),
Rangos_Mg = c("a","a","a","a","a","a","a"),
Media_Fe = c(27.00000,30.25000,68.87500,67.42857,85.12500,63.42857,71.25000),
SE_Fe =c(11.60294,11.60294,11.60294,12.40406,11.60294,12.40406,11.60294),
Rangos_Fe = c("b","bc","a","a","a","ab","a")
)
#plotting in ggplot2
escala_factor <- max(datos_graficos$Media_Fe)/max(datos_graficos$Media_Mg)#variable de la izquierdo/derecho
library(ggplot2)
library(ggrepel)
ggplot(datos_graficos, aes(x = Arena)) +
#eje y izquierdo: hierro
geom_line(
aes(y = Media_Fe,
group = 1,
color = "Hierro",
linetype = "solid"
),
size = 0.8) +
geom_point(
aes(y = Media_Fe, color = "Hierro"),
size = 2) + #puntos para hierro
geom_text_repel(
aes(y = Media_Fe, label = Rangos_Fe),
color = "black", size = 3) + #letras para hierro
geom_errorbar(
aes(y = Media_Fe,
ymin = Media_Fe - SE_Fe,
ymax = Media_Fe + SE_Fe,
color = "Hierro"),
width = 0.2, size = 0.5) + #barras de error para Hierro
#eje y derecho: magnesio
geom_line(
aes(y = Media_Mg * escala_factor,
group = 1,
color = "Magnesio",
linetype = "dashed"
), size = 0.8) + #linea para magnesio
geom_point(
aes(y = Media_Mg * escala_factor,
color = "Magnesio"),
size = 2) + #puntos para magnesio
geom_text_repel(
aes(y = Media_Mg * escala_factor,
label = Rangos_Mg),
color = "black", size = 3) + #letras para magnesio
geom_errorbar(
aes(y = Media_Mg * escala_factor,
ymin = Media_Mg * escala_factor - SE_Mg * escala_factor,
ymax = Media_Mg * escala_factor + SE_Mg * escala_factor,
color = "Magnesio"),
width = 0.2, size = 0.5) + #barras de error para magnesio
scale_y_continuous(
name = "Hierro (mg/kg)", #eje y izquierdo
sec.axis = sec_axis(#eje y derecho
~./escala_factor, name = "Magnesio (%)",
),
limits = c(0, 100)) + #limites al eje y izquierdo
labs(x = "Arena (%)") +
#leyenda
scale_color_manual(
values = c("Hierro" = "black", "Magnesio" = "black"),
guide = "none") +
guides(
linetype = guide_legend(
title = "Elemento",
labels = c("Magnesio", "Hierro"),
values = c("Magnesio" = "dashed", "Hierro" = "solid"),
)) +
theme(
axis.title.y = element_text(size = 10),
axis.title.y.right = element_text(size = 10,color="black"),
axis.text = element_text(size = 8),
legend.key.width = unit(1, 'cm'),
legend.text = element_text(size = 8),
axis.title.y.left=element_text(color="black"),
axis.text.y.left=element_text(color="black"),
axis.text.y.right=element_text(color="black")
)
The code above generates this chart:
Problem: In the legend, how to change the name from “dashed” to “Magnesio” and from “solid” to “Hierro”? The line drawn as dashed is actually for Hierro, the line drawn as solid is really for Magnesio.
Thank you very much for the help.