Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create bar plot with ggplot2 but plot won't produce?

Tags:

r

ggplot2

I am trying to generate a bar plot for the count of workers per salary for each site. The data frame is called "salary_scales_counts_by_site".

Site Managing Operator Operations Technician Process Engineer Senior Process Engineer
Cork 12 16 12 11
LA 6 2 4 1
Dublin 13 17 6 16

I have tried several formulas but something is always missing, I'm going crazy cos I still have to make 4 other graphs that will probably by shambolic too. Any help is much appreciated!

ggplot(salary_scale_counts_by_site, aes(x = salary_scale_counts_by_site, y = `Managing Operator`)) +
   geom_bar(stat = "identity", fill = "green") +
   geom_bar(stat = "identity", x = salary_scale_counts_by_site, y = `Operations Technician`, fill = "blue") +
   geom_bar(stat = "identity", x = salary_scale_counts_by_site, y = `Process Engineer`, fill = "orange") +
   geom_bar(stat = "identity", x = salary_scale_counts_by_site, y = `Senior Process Engineer`, fill = "purple") +
   xlab("Site") +
   ylab("Count") +
   labs(title = "Count of Managing Operators, Operations Technicians, Process Engineers, and Senior Process Engineers per site") +
   theme_classic()

This looks alright to me but I got the following error:

Error: object 'Operations Technician' not found

I just want a bar chart that shows each site and the number of people working under each scale (named as the job title).

like image 480
CM97 Avatar asked Jun 13 '26 18:06

CM97


1 Answers

ggplot works best when your data are in good shape.

So first you need to rearrange them:

x <- salary_scale_counts_by_site %>% 
    pivot_longer(cols = -Site, names_to = "job_title", values_to = "counts")
Site job_title counts
Cork Managing Operator 12
Cork Operations Technician 16
Cork Process Engineer 12
Cork Senior Process Engineer 11
LA Managing Operator 6
LA Operations Technician 2
LA Process Engineer 4
... ... ...

Now as you want bars for site and job you need to combine bars:

ggplot(x, aes(x = job_title, y = counts)) +
  geom_bar(stat = "identity") +
  facet_wrap(vars(Site), nrow = 1)

enter image description here

It needs some polishing, but you got the idea.

like image 61
Marek Avatar answered Jun 16 '26 08:06

Marek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!