Shreya Agarwal
Shreya Agarwal

Reputation: 716

Rowwise coloring in facet_grid in ggplot

I have created a circle grid with each row showing a state's standing on 7 different parameters based on circle sizes. These parameters are in percentage and add up to 100 for each state. For my facet_grid, I'd like to color and size each circle based on the scale for individual states and not as per the entire grid. I'll elaborate on with an example.

circle grid

library(ggforce)
library(tidyverse)
library (ggplot)
library(reshape2)

d <- data.frame("state" = c("Alabama", "Florida", "Washington", "New York"),
       "A" = c(20, 25, 45, 11),
       "B" = c(25, 25, 10, 4),
       "C" = c(50, 5, 20, 5),
       "D" = c(5, 45, 25, 80))

d1 <- melt(d, id.vars = "state")

p3 <- ggplot(d1) +
  geom_circle(aes(x0 = 0.5, y0 = 0.5, r = value, color = "white", fill = value), data = d1) +
  scale_fill_continuous(low = "#5fc5bd", high = "#f37021") +
  scale_color_manual(values = "white") +
  coord_fixed() +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks = element_blank() ,
        legend.position = "none",
        panel.border = element_blank(), 
           axis.title.x=element_blank(),
           axis.title.y=element_blank(),
        axis.text = element_blank())

p3 <- p3 + facet_grid(state ~ variable, labeller=label_wrap_gen(width=10)) +
  theme(strip.text.x = element_text(size = 10, face = "bold"),
          strip.text.y = element_text(size = 10, face = "bold"),
          strip.background = element_rect(colour = "gray", fill = "white"))
p3

As of now the circles on the graph is scaling as per the largest values in the entire dataset. I'd like it to consider values for each state and scale the circle sizes based on the values for each state - so the biggest circle in Alabama should be C, colored orange (highest value for that state) and likewise for other states. Any ideas would be really helpful, thanks.

enter image description here

Upvotes: 2

Views: 161

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174478

You can add a new column to df1 to achieve this:

d1 <- melt(d, id.vars = "state") %>%
      group_by(state) %>%
      mutate(per_state = value/max(value))

Now you set r = per_state and fill = per_state to get this:

enter image description here

Upvotes: 3

Related Questions