user8491385
user8491385

Reputation: 443

Plot order in ggplot by colour and not alphabertical

I have the following code which splits the ggplot by color. Instead of the x axis to be plotted alphabetically is there an easy way to group the bars together so the red bar for example are next to each other? Manually moving them would not be an option as I have many more variables - cheers. enter image description here

mydata <- data.frame(x = c("a", "d", "c", "q", "e", "s", "r", "b"), 
        n = c("UK","EUR","UK", "UK", "EUR", "GLB", "GLB", "EUR"), 
        F = c(-6, 17, 26, -37, 44, -22, 15, 12)) 

ggplot(mydata, aes(x = x, y = F, colour = n, fill =n)) + geom_bar(stat = "Identity")

Upvotes: 0

Views: 265

Answers (2)

pe-perry
pe-perry

Reputation: 2621

Not sure if it is what you want.

I guess you are plotting bar charts, and the bars are currently in alphabetical order like the following example,

library(ggplot2)
library(dplyr)

sample_data <- data.frame(
    city = letters[1:5], 
    value = c(10, 11, 17, 12, 13), 
    country = c("c1", "c2", "c1", "c1", "c2")
)
ggplot(sample_data) + 
    geom_col(aes(x=city, y=value, colour=country, fill=country))

The order of the bars (left to right) is a, b, c, d, e. However, you want the bars ordered by country (the variable determines the colours/fill), i.e. a (c1), c (c1), d (c1), b (c2), e (c2).

To do this, you can set the 'correct' order of city using factor(city, levels=...). Since you want to sort city by country, the levels would be city[order(country)].

sample_data <- sample_data %>% 
    mutate(city2 = factor(city, levels=city[order(country)]))
ggplot(sample_data) + 
    geom_col(aes(x=city2, y=value, colour=country, fill=country))

Upvotes: 1

Roman
Roman

Reputation: 17648

You can try:

library(tidyverse)
mydata %>% 
  mutate(x1 = factor(x, levels=x[order(n,F)])) %>% 
   ggplot(aes(x = x1, y = F, colour = n, fill =n)) + 
   geom_col()

enter image description here

Upvotes: 1

Related Questions