Laura
Laura

Reputation: 535

Connected dotplot with ggplot. Connecting with geom_line

This is my data frame:

df<-structure(list(category_of_job = structure(1:27, .Label = c("Recepcionist", 
"Secretaries", "Admin", "Stock control", "Government admin", 
"Payroll & accounts", "Human resources", "Research admin", "Accounts", 
"Paramedics", "Childcare", "Teaching assistants", "Care workers", 
"School crossing", "Nurses", "Social workers", "Teaching & education", 
"Medical practitioners", "Culture & Media", "Graphic designers", 
"Arts & media", "Designers", "Public relations", "Web Design", 
"Media professionals", "Business & media", "Advertising"), class = "factor"), 
    female_year_salary = c(13, 15, 15, 16, 18, 18, 25, 32, 30, 
    23, 35, 12, 12, 13, 3, 27, 30, 45, 26, 16, 23, 25, 26, 27, 
    29, 32, 34), male_year_salary = c(14, 16, 19, 21, 23, 26, 
    30, 35, 41, 37, 13, 14, 16, 4, 32, 33, 36, 78, 25, 27, 31, 
    31, 27, 29, 34, 37, 40)), row.names = c(NA, -27L), class = c("tbl_df", 
"tbl", "data.frame"))

I need to connect the dots using geom_line() function from ggplot. Is it possible?

I was able to do with geom_segment() But I cant do it with geom_line.

Any help?

ggplot(df, aes(x = category_of_job,group = category_of_job)) +
  geom_point(aes(y = male_year_salary), color = 'red')+
  geom_point(aes(y = female_year_salary), color = 'blue')

How can I connect the red and blue dots with geom_line?

Upvotes: 2

Views: 74

Answers (1)

akrun
akrun

Reputation: 887501

Maybe we can reshape into 'long' with pivot_longer (from tidyr), then use both geom_line and geom_point

library(dplyr)
library(tidyr)
library(ggplot2)
df %>%
      pivot_longer(cols = -category_of_job) %>% 
      ggplot(aes(x = category_of_job, group = category_of_job)) + 
       geom_line(aes(y = value)) + 
         geom_point(aes(y = value, color = name)) +
         theme_bw() +
         theme(axis.text.x = element_text(angle=90, hjust=1), 
             legend.position = "none")           

-output

enter image description here

Upvotes: 2

Related Questions