0

I searched about my problem but apparently, there is no topic about this. Any help will be appreciated.

Suppose I have a plot generated by:

library(tidyverse)

df<- data.frame(PCP = c("BOB","FRED","ED","Other"),
                closed = c(42,64,45,1812), 
                total= c(53,81,58,3188), 
                percentage = c(.7924,.7901,.7758,.5683),
                row= c(1, 2, 3,4),
                color =c("0099FF","#CCCCCC","#CCCCCC","#660033"),
                color_fill = c("99","0","0","98"
                ))

col  <- c(
  "99" = "#0099FF",
  "98" = "#660033", 
  "0" = "#CCCCCC" 
)

df %>%  
  arrange(desc(percentage)) %>% 
  mutate(PCP = PCP,
         closed = closed,
         total = total,
         percentage = percentage,
         row = row,
         color = color,
         color_fill = color_fill) -> df1

ggplot(df1,aes(x=PCP, y = percentage,fill=color_fill, color = color)) +
  geom_col() +
  coord_flip() +
  labs(x ="PCP Name",
       y = "Percentage of Gap Closures",
       title =  "TOP 10 PCPs")+
  scale_fill_manual(values = col)+
  scale_color_manual(values = col) +
  theme(legend.position = "none",
        panel.grid = element_blank(),
        panel.background = element_blank(),
        text = element_text(size=15),
        plot.caption = element_text(hjust = 0, face= "italic"),
        axis.text.y = element_text(colour = col ))

How can I put 0.6 on the x-axis and FRED on the y-axis inside a colored box?

Apex
  • 1,055
  • 4
  • 22
  • 1
    Perhaps have a look here first: [Plot coloured boxes around axis label](https://stackoverflow.com/questions/56543485/plot-coloured-boxes-around-axis-label) – HongboZhu Oct 29 '20 at 09:17
  • This does not help, unfortunately, because my labels are different on both axes. – Apex Oct 29 '20 at 09:35

1 Answers1

1

have a look here by using two annotate (note coord_filp() is updated)

enter image description here

ggplot(df1,aes(x=PCP, y = percentage,fill=color_fill, color = color)) +
  geom_col() +
  #coord_flip() +
  labs(x ="PCP Name",
       y = "Percentage of Gap Closures",
       title =  "TOP 10 PCPs")+
  scale_fill_manual(values = col)+
  scale_color_manual(values = col) +
  theme(legend.position = "none",
        panel.grid = element_blank(),
        panel.background = element_blank(),
        text = element_text(size=15),
        plot.caption = element_text(hjust = 0, face= "italic"),
        axis.text.y = element_text(colour = col )) +
  annotate("rect", xmin = 2.8, xmax = 3.2, ymin = -0.091, ymax = -0.045, alpha=0.5, fill="red") +
  annotate("rect", xmin = 0.2, xmax = 0.35, ymin = 0.58, ymax = 0.62, alpha=0.5, fill="red") +
  coord_flip(xlim = c(1,4), ylim = c(0, 0.8), clip = "off")

If you insist on a "box", then perhaps use segment instead of rect for the annotate.

HongboZhu
  • 4,442
  • 3
  • 27
  • 33