Home > database >  Reverse order of bar chart colours while keeping legend order and colours
Reverse order of bar chart colours while keeping legend order and colours

Time:03-15

I am working on ggplot2 in R, and have used automatic colouring for the plot. It plots stacked bar charts and then converts them to the pie chart. Here is the code:

ggplot(data=reg_sub_rj_reviewed, aes(x=factor(1), stat="bin", fill=`project-effort`))   
  geom_bar(position="fill")   # Stacked bar chart
  facet_grid(facets=. ~ strength)   # Side by side bar chart
  coord_polar(theta="y")   # side by side pie chart
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank()
        )  
  labs(
    x = "",
    y = "Graded Result (code quality)",
    title = "Graded Result Broken Down By Coding Effort",
    fill = "Project Effort"
  )  
  NULL

The resulting image is: enter image description here

I would like the pie chart to have the same order of colours as the legend (when you look at pie chart in a clock-wise way). Start from 12 o'clock and go clockwise: first colour should be orange, then brown, then green etc (currently clockwise plot of pie chart is from the pink (last value!), then purple etc).

PS Also, how can I get rid of the 1 being plotted on the left side of the chart?

A reproducible example of the above issue, is pretty much for any pie chart, for example:

slices <- c(10, 12, 4, 16, 8) 
lbls <- c("1st", "2nd", "3rd", "4th", "5th")
pie(slices,labels = lbls, col=rainbow(length(lbls)),
   main="Pie Chart of Countries")

Result: enter image description here

Humanly I'd expect clockwise numbering 1st, then 2nd (not 5th) in the image, i.e. not anticlockwise. (Sorry I don't know why the image is coming up so huge).

CodePudding user response:

Try aes(x="", ... in ggplot and maybe adjust start = ... or direction = ... in coor_polar.

CodePudding user response:

pi_df <- data.frame(slices, lbls)

library(dplyr); library(forcats)
pi_df %>%
  mutate(lbls = fct_inorder(lbls) %>% fct_rev) %>%
  ggplot(aes(x=slices, y = factor(1), fill = lbls))  
  geom_col()  
  guides(fill = guide_legend(reverse = TRUE))  
  coord_polar()

enter image description here

  • Related