0
votes

I have a data set Region as below.

Region   Color    0-25    25-50     50-75   75-100

AF       Green      51%     14%     24%     11%

AP       Red        5%      12%     9%      74%

EU       Yellow     18%     3%      36%     43%

Global   Green      34%     11%     19%     36%

LA       Green      44%     23%     22%     11%

NA       Green      100%    0%      0%      0%

I would like to plot a stacked bar graph using ggplot for the above data set. I am looking for:, say when Global data is plotted, I Would like the color to be Green for range between 0-25 , dark green for 25-50, light Grey color for 50-75 and dark Grey between 75-100. Simmilary for the others, red, dark red, Light grey and dark grey for AP region.

Something on the similar lines:this post

Any tips on this would be of a much help. Thanks..

1

1 Answers

0
votes

Here is an approach, using green.

dput(df)
structure(list(Region = structure(c(1L, 2L, 3L, 4L, 5L, NA), .Label = c("AF", 
"AP", "EU", "Global", "LA", "Region"), class = "factor"), Color = structure(c(2L, 
3L, 4L, 2L, 2L, 2L), .Label = c("Color", "Green", "Red", "Yellow"
), class = "factor"), `0-25` = c(51, 5, 18, 34, 44, 100), `26-50` = c(14, 
12, 3, 11, 23, 0), `51-75` = c(24, 9, 36, 19, 22, 0), `76-100` = c(11, 
74, 43, 36, 11, 0)), .Names = c("Region", "Color", "0-25", "26-50", 
"51-75", "76-100"), row.names = 2:7, class = "data.frame")

Then, melt served as tidyr and cut created the factor for colors.

df.m <- melt(df, id.vars = "Region", measure.vars = 3:6)
df.m$color.bin <- cut(x = df.m$value, breaks = c(0, 26, 51, 76, 100))
df.m$color.bin <- as.factor(df.m$color.bin)

EDIT AFTER COMMENTS

I then added a factor variable for ggplot to use.

df.m$shade <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "p","p","p","p","p","p","p","p")

The final step was a first run with ggplot and stacking and to set the colors for fill manually. Although there are six regions, I matched your color scheme for the first four only. You can complete the rest. I added the color argument to show divisions between the stacked segments. I added the guides call to eliminate the long legend of letters and colors:

ggplot(df.m, aes(x = Region, y = value, fill = shade)) +  
  geom_bar(stat = "identity", position = "stack", color = "black") + 
  scale_fill_manual(values = c("forestgreen", "lightcoral", "lemonchiffon", "blue", "grey30", "grey30",
                               "lightgreen", "lightcoral", "lemonchiffon", "lightblue", "grey30", "grey30",
                               "lightgreen","lightcoral", "yellow", "lightblue", "grey30", "grey30", 
                               "lightgreen", "grey70","yellow", "blue", "grey30", "grey30")) +
  guides(fill = FALSE)

enter image description here