How to create a legend using the function "legend" if my labels are hour data?

I have a problem. If i create a graphic using the function "plot" with time data vs temperature data and then i want make a legend with funtion "legend", i don't know what write in "x"(this define the position) because this data aren't "numeric", are "POSIXct".
What i do now? :smiley:

Data

head(temp_peces)
Hora Temperatura Condición
1 1899-12-31 00:00:00 18.0 Estable
2 1899-12-31 00:30:00 18.5 Estable
3 1899-12-31 01:00:00 18.0 Estable
4 1899-12-31 01:30:00 18.0 Estable
5 1899-12-31 02:00:00 18.0 Estable
6 1899-12-31 02:30:00 18.0 Estable

type of data

lapply(temp_peces, class)
$Hora
[1] "POSIXct" "POSIXt"
$Temperatura
[1] "numeric"
$Condición
[1] "factor"

Graphics

plot(temp_peces$Hora,temp_peces$Temperatura,col=temp_peces$Condición,pch=19,main = "Temperatura diaria",xlab = "Hora",ylab = "Temperatura (°C)",cex=2)

Temperatura%20peces%20prueba

i want make a legend, but the position in "x" are not valid

legend(x=2,y=22,legend=levels(temp_peces$Condición),col = c(1:3),pch = 19)

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

2 Likes

Thanks for adding the reprex but have in minde that you are not using a copy/paste friendly format and your reprex is not self contained making it harder to help you, in case you prefer here is the spanish version of the reprex guide

About your question, you just have to use a POSIXct value for the x axis, see this example.

temp_peces <- data.frame(stringsAsFactors=FALSE,
                         Hora = as.POSIXct(c("1899-12-31 00:00:00", "1899-12-31 00:30:00",
                                  "1899-12-31 01:00:00", "1899-12-31 01:30:00",
                                  "1899-12-31 02:00:00", "1899-12-31 02:30:00")),
                         Temperatura = c(18, 18.5, 18, 18, 18, 18),
                         Condición = as.factor(c("Estable", "Estable", "Estable", "Other Value", "Other Value",
                                                 "Other Value"))
)

plot(temp_peces$Hora,
     temp_peces$Temperatura,
     col = temp_peces$Condición,
     pch = 19,
     main = "Temperatura diaria",
     xlab = "Hora",
     ylab = "Temperatura (°C)",
     cex = 2)

legend(x = as.POSIXct("1899-12-31 01:30:00"),
       y = 18.4,
       legend = levels(temp_peces$Condición),
       col = c(1:3),
       pch = 19)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.