freddywit
freddywit

Reputation: 321

How to not manually insert rectangles to axis

Ciao guys,

I have the following dataframe

obj <- data.frame (percentile = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6 , 0.7, 0.8, 0.9, 1),
                   emp_change = c(0.05, 0.04, 0.03, 0.05, 0.06, 0.04, 0.02, 0.09, 0.08, 0.06), 
                   task = c("Manual", "Manual", "Manual", "Routine-Manual", "Routine-Manual",
                            "Routine-Abstract", "Routine-Abstract", "Abstract", "Abstract", "Abstract"))

My goal is to display the variable task on my x axis as well. For instance, the 4 values should be displayed as background rectangles. The first rectangle should range 0.1 to 0.4, the second from 0.4 to 0.6, and so on ...

I know how to incorporate them manually e.g. in plotly

...shapes = list(list(type = "rect", fillcolor = "rgb(158,202,225)", 
  line = list(color = "rgb(158,202,225)"), opacity = 0.4,
         x0 = "2007-12-01", x1 = "2009-06-01", xref = "x", ...

This is my plot. Note also, that I use in my real data geom_smooth rather than geom_line.

plot <- ggplot() +
  geom_line(data = obj, aes(x= percentile, y= emp_change, group = 1, color="observed", linetype = "observed"), 
      size=1.5, linetype = "dotdash")
print(plot +  theme(axis.text.x=element_text(angle = 60, hjust = 1)) + 
        theme(axis.title=element_text(size=12)) +
        labs(y="100 x Change in Employment Share", x = "Percentile ranked by task input and log of mean occupational wage (1990)"))

Many thanks in advance

Freddy

Upvotes: 0

Views: 32

Answers (1)

Jon Spring
Jon Spring

Reputation: 66490

I'd suggest determining how you want the summary and feeding that in as a table to other geoms:

library(dplyr)
summary_text <- obj %>%
  group_by(task) %>%
  summarize(min = min(percentile),
            max = max(percentile),
            avg_y = mean(emp_change))

library(ggplot2)          
ggplot() +
  geom_rect(data = summary_text,
            aes(xmin = min - 0.05, xmax = max + 0.05, 
                ymin = avg_y-0.002, ymax = avg_y+0.002), alpha = 0.2) +
  geom_text(data = summary_text, alpha = 0.3,
            aes(x = min - 0.04, y = avg_y, label = task), hjust = 0) +
  
  geom_line(data = obj, 
            aes(x= percentile, y= emp_change, group = 1, 
                color="observed", linetype = "observed"), 
            size=1.5, linetype = "dotdash") + 
  theme(axis.text.x=element_text(angle = 60, hjust = 1)) + 
  theme(axis.title=element_text(size=12)) +
  labs(y="100 x Change in Employment Share", x = "Percentile ranked by task input and log of mean occupational wage (1990)")

enter image description here

Upvotes: 1

Related Questions