Having this dataframe,
ggp <- data.frame(
stringsAsFactors = FALSE,
Month = c("01-2021", "02-2021", "03-2021", "04-2021"),
Eur = c(4666395L, 6710095L, 8426865L, 7365811L),
Tons = c(7677L, 11092L, 13930L, 11709L)
)
and making a multi line chart
ggplot(ggp, aes(Month)) +
geom_line(aes(y = Eur), colour = "red", group = "Eur") +
geom_line(aes(y = Tons), colour = "blue", group = "Tons")
How can I make the graph show the last two values of each category as label? i.e. the last value of Eur (7365811) and Tons (11709). Any idea?
Thanks in advance
ggp <- data.frame(
stringsAsFactors = FALSE,
Month = c("01-2021", "02-2021", "03-2021", "04-2021"),
Eur = c(4666395L, 6710095L, 8426865L, 7365811L),
Tons = c(7677L, 11092L, 13930L, 11709L)
)
last_df <- slice_tail(ggp,n=1) %>% pivot_longer(cols = -Month)
ggplot(ggp, aes(Month)) +
geom_line(aes(y = Eur), colour = "red", group = "Eur") +
geom_line(aes(y = Tons), colour = "blue", group = "Tons")+
geom_label(data=last_df,mapping = aes(y=value,label=value),
nudge_x = .1)
2 Likes
Great. Many thanks nirgrahamuk. Can the box be removed?
Great, thanks again, it's ok.
If I do this
ggpLong <- ggp %>% pivot_longer(cols = Eur:Tons, names_to = "Category", values_to = "Value")
to have the legend and then
ggplot(ggpLong, aes(x = Month, y = Value, color = Category, group = Category)) + geom_line() +
geom_label(data=last_df,mapping = aes(y=value,label=value), nudge_x = .1)
I get this error
Error in FUN(X[[i]], ...) : object 'Category' not found
I would guess that last_df doesn't have the Category variable
system
Closed
8
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.