Home > Blockchain >  put legend of area chart inside the figure
put legend of area chart inside the figure

Time:03-13

here is my data and my area chart:

df<- data.frame(age=15:40,h1= 25:50,h2=35:60,h3=45:70)
data1<- df %>% gather(timeuse, minute, -age)

ggplot(data1, aes(x = age, y = minute, fill = timeuse))  
  geom_area()  
  scale_fill_brewer(palette = "Gray") 
  scale_x_continuous(breaks = seq(15, 90, by = 5))  
  scale_y_continuous(breaks = seq(0, 1500, by = 100)) 
  theme_classic() 

I want to put legend inside the area chart like this picture:

enter image description here

CodePudding user response:

In general that could be easily achieved using geom_text with position = position_stack(vjust = 0.5). Depending on your real data the tricky part would be to select the x positions where you want to place the labels. In my code below I use dplyr::case_when to set different positions for each category of timeuse. Additionally depending on your real data it might be worthwhile to have a look at ggrepel::geom_text_repel.

library(ggplot2)
library(dplyr)

data1 <- data1 %>% 
  mutate(label = case_when(
    timeuse == "h3" & age == 20 ~ timeuse,
    timeuse == "h2" & age == 27 ~ timeuse,
    timeuse == "h1" & age == 35 ~ timeuse,
    TRUE ~ ""
  ))

p <- ggplot(data1, aes(x = age, y = minute, fill = timeuse))  
  geom_area()  
  scale_fill_brewer(palette = "Greys") 
  scale_x_continuous(breaks = seq(15, 90, by = 5))  
  scale_y_continuous(breaks = seq(0, 1500, by = 100)) 
  theme_classic()

p   
  geom_text(aes(label = label), position = position_stack(vjust = 0.5))  
  guides(fill = "none")

CodePudding user response:

You can do it manually with annotate

annotate("text", x=50, y=2, label= "market work")

or more automated, something like this (play with the selection of rows where you want to place them):

  geom_text(data = df%>% group_by(timeuse) %>% sample_n(1),
            aes(x = Age, y = minute, 
                label = rev(timeuse), color = rev(timeuse)),
            position = position_stack(vjust = 0.5)) 
  • Related