Home > Software engineering >  unstack stacked ggplot legend
unstack stacked ggplot legend

Time:06-12

I'm working with a chemistry dataset, where I have 11 different chemicals, here labeled under the column c1,c2,...c11

I have made pie charts using library(ggplot2) , and would like to do 2 things with my plot.

  1. Display all variables in the legend in a horizontal fashion (done), and not have them stacked (not done), as you see in my example. Having just one line would be great. 2 lines could also be acceptable.
  2. Change colors to be color-blind friendly

Here is a pretend dataset we can work with so you can see what I have at this point. I have tried searching "legend margins" to increase the area the legend is plotted on, but to no avail.

data <- read.delim("https://pastebin.com/raw/MS5GLAxa", header = T)


ggplot(data, aes(x="", y=ratio, fill=chemical))  
  geom_bar(stat="identity", width=1,position = position_fill())   facet_wrap(~treatment, nrow=1) 
  coord_polar("y", start=0) 
  theme_void(base_size = 20) 
  theme(legend.position=c(0.5, 1.2),legend.direction = "horizontal") 
  theme(plot.margin=unit(c(0,0,0,0), 'cm'))

enter image description here

Some side bonuses here would be to be able to:

  • increase the size of the pie chart (I believe I achieved this with making my margins as small as possible on the sides)
  • have the pie chart have solid colors, and no white lines in graph

CodePudding user response:

Use guides to make the number of rows to 1 and use scale_fill_brewer with color blindness friendly palette.

ggplot(data, aes(x="", y=ratio, fill=chemical))  
  geom_bar(stat="identity", width=1,position = position_fill())   
  facet_wrap(~treatment, nrow=1) 
  coord_polar("y", start=0)  
  scale_fill_brewer(palette="Paired")   
  theme_void(base_size = 20)  
  theme(legend.position=c(0.5, 1.5),legend.direction = "horizontal",
        plot.margin=unit(c(0,0,0,0), 'cm'))   
  guides(fill = guide_legend(nrow = 1)) # if required nrow = 2

enter image description here

  • Related